gpt4 book ai didi

javascript - 随机数选择后如何从列表中删除项目

转载 作者:行者123 更新时间:2023-12-04 07:45:29 25 4
gpt4 key购买 nike

所以我正在为计算机科学类(class)制作一个应用程序,基本上,前提是你在披萨店工作,你必须选择客户想要的配料,这些配料是随机选择的。目前,我有一个列表中的浇头,可以用 randomNumber() 选择它们,但我不知道如何在选择后删除浇头,以避免重复。

    var toppings = ["pepperoni", "mushrooms", "pineapple", "peppers", "sausage", "sardines", 
"bacon"];
function newCustomer() {
showElement("customerPic");
for (var i = 0; i < 3; i++) {
toppings[(randomNumber(0, 6))];
console.log(("I would like " + toppings[(randomNumber(0,6))]) + " on my pizza,
please");
}
}

最佳答案

对我来说,最简单的方法似乎是创建一个新数组,其中包含原始 toppings 中的字符串。数组,但按随机顺序 - 您可以将该数组视为堆栈并继续从其中弹出随机元素,直到没有剩余元素为止。有关更多详细信息,请参阅代码注释:

// Your original data
var toppings = [
"pepperoni",
"mushrooms",
"pineapple",
"peppers",
"sausage",
"sardines",
"bacon"
];

// A new array that contains same strings as `toppings`, but their order's randomized
const shuffledToppings = [...toppings].sort(() => Math.random() - 0.5);

// `pop` is an Array.prototype function that removes the and returns the last item in the array - this means `shuffledToppings` is shrinks by 1 each time this function is called
function newCustomer() {
console.log(`I'd like a pizza with ${shuffledToppings.pop()}`);
}

// Call `newCustomer` function until all strings have been popped off `shuffledToppings` (i.e.< it is empty).
while (shuffledToppings.length > 0) {
newCustomer();
}

引用: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop

关于javascript - 随机数选择后如何从列表中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67217667/

25 4 0
文章推荐: Java - List 类型的方法 descendingIterator() 未定义