鴻蒙傳說(shuō)
2023-03-18 17:27:29
我正在嘗試造一個(gè)從數(shù)組中隨機(jī)選擇項(xiàng)目?jī)纱蔚木渥?。第一個(gè)選擇的項(xiàng)目暫時(shí)從數(shù)組中刪除,因此不能再次選擇,然后第二個(gè)項(xiàng)目也被隨機(jī)選擇并添加到句子中。然后,為了重置它以便稍后可以再次執(zhí)行此操作,我嘗試將第一個(gè)選擇的項(xiàng)目添加回其初始數(shù)組。問(wèn)題是,當(dāng)我這樣做時(shí),chosenWord1 在句子中顯示為我希望的字符串,但 chosenWord2 顯示的是索引號(hào)。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);另外,如果有一些更明智的方法可以構(gòu)建它,請(qǐng)告訴我。我對(duì)此還是很陌生。
1 回答

PIPIONE
TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超9個(gè)贊
我不知道這是否是您需要的,但這會(huì)重復(fù)提取兩個(gè)隨機(jī)單詞,而不是將它們從原始數(shù)組中取出。for 循環(huán)用于顯示它如何處理不同的單詞。
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}`);
}
添加回答
舉報(bào)
0/150
提交
取消