JavaScript循环遍历数组并从随机输入数字中替换所有数字,直到array = 0

时间:2018-02-11 12:06:37

标签: javascript arrays loops

我有一个数组,然后我有一个随机数输入,如果进入数组,则将值更改为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);

1 个答案:

答案 0 :(得分:0)

您可以尝试在Array.prototype.indexOf()内利用while statement

请参阅下面的粗略示例。

&#13;
&#13;
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;
&#13;
&#13;