JavaScript 中 Array.forEach方法使用注意事项
如果你专注于前端,那么这个问题你可能不会遇到,但是如果你写C#,可能就会遇到这个问题。
现象:
function forEachDemo()
{
var re;
arr.forEach(function (item, i) {
if (i > 3)
{
re = i;
return;
}
});
return re;
}
var result = forEachDemo();
console.log("result:"+result);
结果输出:result:5
结论:
return没有结束forEach的循环!
"forEach() executes the callback function once for each array element; unlikemap()
or
reduce() it always returns the value
undefined and is not chainable."原来forEach不支持返回值,不能像C#那样返回特定值。
但是是不是return在forEach中就不起作用了呢?
function forEachDemo()
{
arr.forEach(function (item, i) {
if (i > 3)
{
console.log("i top:" + i);
return;
}
if (i > 3) {
re = i;
console.log("i bottom:" + i);
}
});
}
forEachDemo();结果输出:i top:4
i top:5
结论:return结束了当前循环,类似于continue的作用
相关总结:
map():返回一个新的Array,每个元素为调用func的结果
filter():返回一个符合func条件的元素数组
some():返回一个boolean,判断是否有元素是否符合func条件
every():返回一个boolean,判断每个元素是否符合func条件
forEach():没有返回值,只是针对每个元素调用func
参考:
http://blog.csdn.net/github_31392345/article/details/48631067
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
- 上一篇:没有了
- 下一篇:没有了
