嵌套循环中的意外结果

时间:2021-03-19 11:32:32

标签: javascript arrays loops for-loop nested-loops

let conditon = false

const test = [2, 0, 3, 4, 5, 6, 7]
for (let i = 0; i < 10; i++) {
  for (let j = 0; j < test.length; j++) {
    if (0 !== test[j]) {
      conditon = true;
       break;
    }else{
      conditon = false;
      break;
    }
  }
  console.log(conditon)
}

在这个循环中,console.log 为 true,但当它在数组中找到 0 时应该打印 false

3 个答案:

答案 0 :(得分:1)

您不断将 condition 设置为 true,因为例如0 !== 2 评估为真。对于每个元素都是这种情况,除了 0。0 !== 0 其计算结果为 false。您需要在那里放置一个 else 检查并将 condition 设置为 false,然后通过将 condition 设置回 true 以在下一次迭代中重新设置,使其不会继续并再次覆盖您的值。< /p>

let condition = false;

const test = [2, 0, 3, 4, 5, 6, 7]
for (let i = 0; i < 10; i++) {
  for (let j = 0; j < test.length; j++) {
    if (0 !== test[j]) {
      conditon = true;
    } else {
      conditon = false;
      break;
    }
  }

  console.log(conditon)

  // Comment this part out if you want it to continue looping without immediately stopping.
  // Otherwise the loop ends once it hits 0.
  if(!condition)
    break;
}

这不是最好的方法,请注意……我只是为您提供一个示例,说明为什么您的代码会以这种方式工作。

答案 1 :(得分:0)

这是一个简化版本,您可以检查它的工作原理,如果需要,您可以将其用作更复杂版本的模板。

let condition;
const nums = [2, 0, 3, 4, 5, 6, 7];

for(let i = 0; i < 2; i++){
  for (let num of nums) {
    condition = (num !== 0);
    console.log(num, condition);
  }
  console.log("\n--end of outer loop--\n\n");
}


编辑
从您的评论中,我了解到在每次通过外循环后,您想报告数组中是否有任何值为零。如果这是您要查找的内容,您可以执行以下操作:

    const nums = [2, 0, 3, 4, 5, 6, 7];

    for(let i = 0; i < 2; i++){
      let noZerosFound = true;
      console.log("checking: " + nums);
      for (let num of nums) {
        if(num === 0){
          noZerosFound = false;
          // Can include a `break` statement here for better performance
        }
      }
      console.log("noZerosFound: " + noZerosFound);
      console.log("\n");
    }


而且 JavaScript 数组还为这种情况提供了一些有用的内置方法。所以如果你愿意,你可以简单地做:

        const nums = [2, 0, 3, 4, 5, 6, 7];

        for(let i = 0; i < 2; i++){
          console.log("checking: " + nums);

          // Applies the function `(num) => num !== 0` to each element of `nums`. 
          //   If the result is true for every element, returns true.  
          //   Otherwise, returns false. 
          const noZerosFound = nums.every( (num) => num !== 0);

          console.log("noZerosFound: " + noZerosFound);
          console.log("\n");
        }

请参阅 MDN 上的 the .every methodarrow functions 以获取进一步说明。

答案 2 :(得分:0)

这里已经有了很好的答案。让我介绍一下这种方式作为额外的答案。

const test = [2, 0, 3, 4, 5, 6, 7];
console.log(!test.includes(0));

const test2 = [2, 1, 3, 4, 5, 6, 7];
console.log(!test2.includes(0));

.includes()

array.includes(<value>)
  • .includes() 如果给定值在数组中,则返回 true,否则返回 false
  • !test.includes(0) 如果 true 不在 0 中,则返回 testfalse 如果 0test 中。