gpt4 book ai didi

javascript - 如何在 Javascript 中使用一个函数为多个变量分配不同的值

转载 作者:行者123 更新时间:2023-11-30 14:30:35 24 4
gpt4 key购买 nike

我有一系列数组,每个数组包含 20 个不同的字符串,基本上是这样的:

const str1a = [
"Text",
"Different text",
"etc",
...
];

const str1b = [
"something else",
"more options",
"and more",
...
];

等等等等。目前我使用下面的代码从每个数组中选择一个随机字符串并将它们连接起来(这是用于诗歌生成器):

const generatorDiv = document.querySelector("#generator");

function writePoem () {
let i = Math.floor(21*Math.random());
let j = Math.floor(21*Math.random());
let k = Math.floor(21*Math.random());
let l = Math.floor(21*Math.random());
let m = Math.floor(21*Math.random());
let n = Math.floor(21*Math.random());
let o = Math.floor(21*Math.random());
let p = Math.floor(21*Math.random());
let q = Math.floor(21*Math.random());
generatorDiv.innerHTML = str1a[i] + str1b[j] + str1c[k] + str1d[l] + "<br />" +
str2a[m] + str2b[n] + str2c[o] + str2d[p] + str2e[q];
}

writePoem ();

我无法弄清楚的是(如果有人问过这个问题,请原谅我,我已经尝试了一堆搜索参数,但感觉好像我没有使用正确的词)...

有没有什么方法可以简化所有让 i、让 j、让 k...?

这是我最好的尝试,但没有成功:

function pickStr () {
Math.floor(21*Math.random());
}

const randomnessStorage = [i, j, k, l, m, n, o, p, q];

for (let a = 0; a < 10; a++) {
let randomnessStorage[a] = pickStr();
}

最佳答案

您的代码几乎是正确的。

您没有在 pickStr 中返回任何内容。

  • 获取数组范围内的随机索引Math.floor(Math.random() * arr.length)
  • 选择一个字符串

const str1a = [
"Can I",
"Did it",
"Was it"
];

const str1b = [
"follow",
"catch",
"drop"
];

const str1c = [
"an apple",
"a car",
"the truck"
];

const str1d = [
"flying",
"driving",
"chewing"
];

function pickStr(arr) {
if (arr) {
let randomIndex = Math.floor(Math.random() * arr.length);
return arr[randomIndex];
} else {
return "-Array Null-";
}
}

function writePoem() {
let div = document.querySelector('#poem-container');
let poemTemplate = `${pickStr(str1a)} ${pickStr(str1b)} ${pickStr(str1c)} ${pickStr(str1d)}`;
div.innerHTML = poemTemplate;
}

writePoem();
<div id="poem-container"></div>

关于javascript - 如何在 Javascript 中使用一个函数为多个变量分配不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51249576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com