聊聊forEach

简介forEach

forEach()方法用于调用数组的每一个元素,并将元素传递给回调函数。数组

注意: forEach()对于空数组是不会执行回调函数的。bash

forEach()是ES5中操做数组的一种方法,主要功能是遍历数组。函数

语法

array.forEach(function(currentValue, index, arr), thisValue)ui

其中:this

  • currentValue 必需。当前元素
  • index 可选,当前元素的索引值
  • arr 可选,当前元素所属的数组对象
  • thisValue 可选,传递给函数的值通常用 "this" 值。若是这个参数为空, "undefined" 会传递给 "this" 值

返回值:undefinedspa

forEach()return不会立马跳出函数,而是继续执行,在文章的后面会具体描述解决办法,先看一些实例:.net

实例

前面也说过,forEach()的主要功能是遍历数组code

var arr=[1,2,3,4];
arr.forEach(alert);   //-> 在页面上弹出数组的值
复制代码

上面也提到了函数的参数,这里写个例子便于理解:cdn

var arr=[1,2,3,4];
arr.forEach(function(value,index,array){
   array[index] == value ;   //-> true
   sum+=value;
});
console.log(sum);  //-> 10
复制代码

关于return的讨论

咱们都知道,在for循环中,跳出循环能够用break,可是在forEach循环遍历中,break会报错,而return也没法跳出循环:对象

var arr=[1,2,3,4,5];
var num=3;
arr.forEach(function(value){
   if(value == num){
       return;
   }
   console.log(value);
});
复制代码

瞧瞧咱们发现了什么了不起的事情!这里的return并无跳出循环返回,而是起到了for循环中continue的做用。

那么咋中断这个forEach呢?

中断forEach的两种方法

第一种:使用try···catch捕获异常实现

try{
    var array=[1,2,3,4,5];
    array.forEach(function(value,index){
       if(value == 3){
           throw new Error("Ending");
       }
       console.log(value)
    });
}
catch(e){
    if(e.message!="Ending"){
        throw e;
    }
}
复制代码

第二种:使用数组中另外两个方法替代: arr.sonme()arr.every()

当some()内部return true时,跳出整个循环

var arr = [1,2,3,4,5];
var num = 3;
arr.some(function(v){
   if(v == num) {
       return true;
   }
   console.log(v);
});
复制代码

当every()内部return false时跳出整个循环

var arr = [1,2,3,4,5];
var num = 3;
arr.every(function(v){
   if(v == num) {
       return false;
   }else{
       console.log(v);
       return true;
   }
});
复制代码


参考: Javascript Array forEach()中没法return和break,代替方法some()与every()

相关文章
相关标签/搜索