返回 bool 值时使用.map()
和for()
有区别吗?请参阅代码示例,其中 for()
循环返回 true,但 .map()
不返回任何内容。
function simpleLoop(theArray) {
// Works as expected
for (var i = theArray.length - 1; i >= 0; i--) {
let value = anObject[theArray[i]];
if (!value || /^\s*$/.test(value)) {
return true;
}
}
}
function simpleMap(theArray) {
// Does not work
theArray.map((language) => {
const value = anObject[language];
if (!value || /^\s*$/.test(value)) {
return true;
}
});
}
simpleLoop(theArray) // <-- returns true
simpleMap(theArray) // <-- returns nothing (?)
最佳答案
当您返回到 for
循环内时,您将从 simpleLoop
函数中返回。当您返回 map
内部时,您是从赋予 map
的匿名函数返回。
我会使用 some
而不是 map
来获得所需的效果:
function simpleSome(theArray) {
return theArray.some((language) => {
const value = anObject[language];
return !value || /^\s*$/.test(value);
});
}
关于javascript - 在 .map() 中返回 bool 值与 for() 循环中的行为不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41940634/