我有一个数组,然后我有一个随机数输入,如果进入数组,则将值更改为0。我必须循环这个随机数,直到我将所有数组的数字更改为0.我无法循环它。我只能替换一个
var array1 = [1, 2, 3, 4, 5];
var n = Math.floor(Math.random() * 5) + 1;
for (var i = 0; i < array1.length; i++) {
if (array1 !== 0) {
if (n == array1[i]) {
array1[i] = 0;
}
continue
}
break
}
console.log(n);
console.log(array1);
答案 0 :(得分:0)
您可以尝试在Array.prototype.indexOf()
内利用while statement
。
请参阅下面的粗略示例。
const array = [1, 2, 3, 4, 5]
const goal = [...array].fill(0)
while (JSON.stringify(array) != JSON.stringify(goal)) {
const n = Math.floor(Math.random() * 5) + 1
console.log(`n: ${n}`)
const index = array.indexOf(n)
if (index >= 0) array[index] = 0
}
console.log(`Complete: ${array}`)
&#13;