JavaScript 中的 forEach 可以返回吗? [英] Can forEach in JavaScript make a return?
问题描述
我想知道 JavaScript 中的 forEach 是否可以返回,这是我的代码:
I wonder if forEach in JavaScript can make a return, here is my code:
var a = [0, 1, 2, 3, 4];
function fn(array) {
array.forEach(function(item) {
if (item === 2) return false;
});
return true;
}
var ans = fn(a);
console.log(ans); // true
我想知道 2 是否在我的数组中,如果是,则返回 false,但似乎 forEach 函数循环了整个数组并忽略了返回.
I want to find out if 2 is in my array, if so, return false, but it seems that the forEach function has looped the whole array and ignore return.
我想知道是否可以使用 forEach 获得我想要的答案(我知道我可以使用 for(..) 获得我想要的答案)?亲爱的朋友,请帮助我,非常感谢!
I wonder if I can get the answer I want with forEach ( I know I can get what I want using for(..))? dear friend, pls help me, with great thanks!
推荐答案
您可以使用 indexOf 代替 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
You can use indexOf instead https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
function fn(array) {
return (array.indexOf(2) === -1);
}
<小时>
同样来自 forEach 的文档 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
注意:除了通过以下方式停止或中断 forEach() 循环抛出异常.如果你需要这样的行为,.forEach()方法是错误的工具,请改用普通循环.
Note: There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behaviour, the .forEach() method is the wrong tool, use a plain loop instead.
因此,不能以您使用的方式使用返回值.但是,您可以执行 throw (不建议这样做,除非您确实需要在那里引发错误)
So, the return value cannot be used the way you are using it. However you could do a throw (which is not recommended unless you actually need an error to be raised there)
function fn(array) {
try {
array.forEach(function(item) {
if (item === 2) throw "2 found";
});
}
catch (e) {
return false;
}
return true;
}
这篇关于JavaScript 中的 forEach 可以返回吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!