返回布尔值时,在使用.map()
和for()
时是否有区别?请参阅代码示例,其中for()
循环返回true,但.map()
不返回任何内容。返回.map()中的布尔值与for()循环中的行为不同?
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 (?)
那'return'是在回调函数,'simpleMap'没有'return'声明。 – Bergi
当您在'for'循环中返回时,您将从'simpleLoop'函数返回。当你在'map'内返回时,你从匿名函数返回。 – Tholle
@Tholle,你会如何让simpleMap返回呢?或者这是不可能的? – NealVDV