![](/img/trans.png)
[英]Loop from 0 to a number and loop through all numbers in array (javascript)
[英]JavaScript Looping through array and replace all numbers untill array = 0 from a random input number
我有一个数组,然后我有一个随机数输入,如果进入数组,则将值更改为 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);
您可以尝试在while statement
利用Array.prototype.indexOf()
。
请参阅下面的粗略示例。
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}`)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.