javascript - 具有嵌套 forEach 和 for 循环的函数不会返回 false

标签 javascript function for-loop foreach return

我正在做 algorithm challenge在 JS 中练习。我有一个通过循环运行的程序,当满足条件时,函数应该返回 false。但是,当条件满足时,返回不起作用,函数总是以返回 true 结束。

const isDiagonalLeftWristband = (band) => {
  band.forEach((row, y) => {
    row.forEach((item, x) => {
      for(let i = 0; (i < band[y].length - x) && (i < band.length - y); i++) {        
        if (band[y][x] !== band[y+i][x+i]) {
          console.log(false) //FALSE GETS OUTPUTTED MULTIPLE TIMES
          return false;
        }
      }
    })
  })
  return true;
}


const band3 = [
  ["A", "B", "C"],
  ["C", "Z", "B"],
  ["B", "C", "A"],
  ["A", "B", "C"]
];

console.log(isDiagonalLeftWristband(band3))


输出:
false //from console log
false //from console log
true //from function return statement

任何帮助将不胜感激!

最佳答案

return false只会退出(item, x) => {}匿名函数而不是 isDiagonalLeftWristband()如您所料。后两个forEach被执行isDiagonalLeftWristband()将永远 return true最后。您可以使用循环来避免此问题。

const isDiagonalLeftWristband = (band) => {
  for (let [y, row] of band.entries()) {
    for (let [x, item] of row.entries()) {
      for(let i = 0; (i < band[y].length - x) && (i < band.length - y); i++) {        
        if (band[y][x] !== band[y+i][x+i]) {
          console.log(false) //FALSE GETS OUTPUTTED MULTIPLE TIMES
          return false;
        }
      }
    }
  }
  return true;
}

const band3 = [
  ["A", "B", "C"],
  ["C", "Z", "B"],
  ["B", "C", "A"],
  ["A", "B", "C"]
];

console.log(isDiagonalLeftWristband(band3))

forEach并非旨在提前终止。它总是会遍历所有元素。 (它的名字:))。来自 MDN 文档:

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Early termination may be accomplished with:

A simple for loop
A for...of / for...in loops
Array.prototype.every()
Array.prototype.some()
Array.prototype.find()
Array.prototype.findIndex()

Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.



您可以改为使用建议的函数之一,该函数旨在使用谓词测试数组的元素。 every()测试数组的所有元素是否都通过了一些测试;这至少在语义上是你需要的。

const isDiagonalLeftWristband = (band) => {
  return band.every((row, y) => {
    return row.every((item, x) => {
      for(let i = 0; (i < band[y].length - x) && (i < band.length - y); i++) {        
        if (band[y][x] !== band[y+i][x+i]) {
          return false;
        }
      }
      return true;    
     });
  });
}

const band3 = [
  ["A", "B", "C"],
  ["C", "B", "B"],
  ["B", "C", "A"],
  ["A", "B", "C"]
];

console.log(isDiagonalLeftWristband(band3))

关于javascript - 具有嵌套 forEach 和 for 循环的函数不会返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61034165/

相关文章:

r - 具有不同列名称的 for 循环中的 left_join

javascript - 仅适用于字符 a-z、A-Z 的正则表达式

javascript - google lighthouse 如何计算 javascript 评估时间,以及为什么对于不同环境中的相同脚本,它会有很大差异

javascript - 如何修复 "the requested module does not provide an export named ' default'"?

algorithm - 我有一个函数 f(w,x,y,z) 和一个目标值 A,如何发现产生 A 的 w,x,y,z 值?

c - C中初学者电话簿应用程序的奇怪输出

c - 错误 : syntax error before 'double'

javascript - 爸爸解析 : Save JSON Output Locally

c++ - C++ 中整数循环和迭代器循环之间的差异

javascript - 如何循环遍历音频文件的 javascript 数组?