gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:42:10 24 4
gpt4 key购买 nike

我正在做 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com