简体   繁体   中英

How to assign multiple variables different values using one function in Javascript

I have a series of arrays, each containing 20 different strings, basically like this:

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

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

Etc, etc. Currently I use the following code to pick a random string from each array and concatenate them (this is for a poetry generator):

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 ();

What I'm having trouble figuring out is (forgive me if this has been asked, I've tried a bunch of search parameters but feel as though I'm not using the right words)...

Is there some way to simplify all that let i, let j, let k...?

This was my best attempt, but it's not doing the trick:

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();
}

Your code was nearly right.

You did not return anything in pickStr .

  • Get a random index in the range of the array Math.floor(Math.random() * arr.length)
  • Pick a string

 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> 

You were going in the right direction. Add a return statement in pickStr function and update your writePoem function like following:

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()];
}

You could store your arrays in an array and create an es6 pickstr function that will return a random floored number.

 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> 

If I were you then I would modify the structure and make it an array of object instead of multiple separate array's :

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

Then I generate the random poem this way:

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM