从数组中取出随机字符串,将其放入新数组中,然后再将其放回旧数组中
take random string from array, put it in new array, then put it back in old array later
我正在尝试造一个从数组中随机选择项目两次的句子。第一个选择的项目暂时从数组中删除,因此不能再次选择,然后第二个项目也被随机选择并添加到句子中。然后,为了重置它以便稍后再次执行此操作,我尝试将第一个选择的项目添加回其初始数组。
问题是,当我这样做时,chosenWord1 在句子中显示为我希望的字符串,但 chosenWord2 显示的是索引号。
array = ["word","another word", "yet another word"];
/* put a random word from the array in its own value and then
remove it from the array so it can't be chosen in next step */
let chosenWord1 = array.splice(Math.random() * array.length, 1)[0];
/* pick another random word from the same, altered array */
let chosenWord2 = Math.floor(Math.random() * array.length);
/* a function that puts a sentence on the webpage concatenating the strings
from chosenWord1 and chosenWord2 goes here. then... */
/* add back the previously removed word so this process can repeat again
with the same items in the array as there was before anything was done to it */
array.splice(1,0,chosenWord1);
此外,如果我有一些更明智的方法来构建它,请告诉我。我对此还是很陌生。
我不知道这是否是您需要的,但这会重复提取两个随机单词,而不是将它们从原始数组中取出。 for 循环用于显示它如何处理不同的单词。
const array = ["word", "another word", "yet another word"];
const randomNumber = (key) => Math.floor(Math.random() * key);
for (let i = 0; i < 10; i++) {
const { [randomNumber(array.length)]: wordOne, ...rest } = array;
const { [randomNumber(array.length - 1)]: wordTwo } = Object.values(rest);
console.log(`${wordOne} and ${wordTwo}`);
}
我正在尝试造一个从数组中随机选择项目两次的句子。第一个选择的项目暂时从数组中删除,因此不能再次选择,然后第二个项目也被随机选择并添加到句子中。然后,为了重置它以便稍后再次执行此操作,我尝试将第一个选择的项目添加回其初始数组。
问题是,当我这样做时,chosenWord1 在句子中显示为我希望的字符串,但 chosenWord2 显示的是索引号。
array = ["word","another word", "yet another word"];
/* put a random word from the array in its own value and then
remove it from the array so it can't be chosen in next step */
let chosenWord1 = array.splice(Math.random() * array.length, 1)[0];
/* pick another random word from the same, altered array */
let chosenWord2 = Math.floor(Math.random() * array.length);
/* a function that puts a sentence on the webpage concatenating the strings
from chosenWord1 and chosenWord2 goes here. then... */
/* add back the previously removed word so this process can repeat again
with the same items in the array as there was before anything was done to it */
array.splice(1,0,chosenWord1);
此外,如果我有一些更明智的方法来构建它,请告诉我。我对此还是很陌生。
我不知道这是否是您需要的,但这会重复提取两个随机单词,而不是将它们从原始数组中取出。 for 循环用于显示它如何处理不同的单词。
const array = ["word", "another word", "yet another word"];
const randomNumber = (key) => Math.floor(Math.random() * key);
for (let i = 0; i < 10; i++) {
const { [randomNumber(array.length)]: wordOne, ...rest } = array;
const { [randomNumber(array.length - 1)]: wordTwo } = Object.values(rest);
console.log(`${wordOne} and ${wordTwo}`);
}