如何使用JavaScript中的一个函数为多个变量分配不同的值

时间:2018-07-09 15:54:37

标签: javascript arrays

我有一系列的数组,每个数组包含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();
}

4 个答案:

答案 0 :(得分:2)

您的代码几乎正确。

您在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>

答案 1 :(得分:0)

您朝着正确的方向前进。在return函数中添加pickStr语句,并更新您的writePoem函数,如下所示:

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

function writePoem () {
  generatorDiv.innerHTML = str1a[pickStr()] + str1b[pickStr()] + str1c[pickStr()] + str1d[pickStr()] + "<br />" +
    str2a[pickStr()] + str2b[pickStr()] + str2c[pickStr()] + str2d[pickStr()] + str2e[pickStr()];
}

答案 2 :(得分:0)

您可以将数组存储在数组中,并创建一个es6 pickstr函数,该函数将返回一个随机底数。

 function writePoem () {
 let pickstr = () => Math.random() * 21 | 0,
 output = [str1a, str1b, str1c, str1d, str2a, str2b, str2c, str2d, str2e].map(str=>str[pickstr()]); 
 output.splice(4,0, "<br />")
 generatorDiv.innerHTML = output.join("");
 }

 writePoem ();

const str1a = ["one.", "two.", "three.", "four."],
  str1b = ["five.", "six.", "seven.", "eight."],
  str1c = ["nine.", "ten.", "eleven.", "twelve."]; let generatorDiv = document.querySelector("#gendiv");

function writePoem() {
  let pickstr = () => Math.random() * 4 | 0,
  output =  [str1a, str1b, str1c, str1a, str1b, str1c].map(str => str[pickstr()]);
  output.splice(3,0, "<br/>");
  generatorDiv.innerHTML = output.join("");
}

writePoem();
<div id="gendiv"></div>

答案 3 :(得分:0)

如果我是我,那么我将修改结构并将其设置为对象数组,而不是多个单独的数组

var str = [{
    'str1a': ["Text",
      "Different text",
      "etc",
    ]
  },
  { 'str1b': [...] },
  { 'str1c': [...] },
  { 'str1d': [...] }
];

然后我以这种方式生成随机诗:

const generatorDiv = document.querySelector("#generator");
var str = [{
    'str1a': ["Text",
      "Different text",
      "etc",
    ]
  },
  {
    'str1b': [
      "something else",
      "more options",
      "and more",
    ]
  },
  {
    'str1c': [
      "anything else",
      "les options",
      "or more",
    ]
  },
  {
    'str1d': [
      "else",
      "less",
      "more",
    ]
  }
];

function pickStr(arr) {

  let ran = Math.floor(Math.random() * arr.length);
  return arr[ran];

}
result = [];
str.forEach(myFunction);

function myFunction(item, index) {

  for (var key in item) {
    result.push(pickStr(item[key]))
  }
}
console.log(result.join(' '))
generatorDiv.innerHTML = result.join(' ');
<div id="generator"></div>