浅谈JavaScript中forEach与each

来源:互联网 发布:mac office2016破解版 编辑:程序博客网 时间:2024/06/07 05:23

https://www.cnblogs.com/fangshidaima/p/5910604.html


forEach是ES5中操作数组的一种方法,主要功能是遍历数组,例如:

  

1
2
vararr = [1,2,3,4];
arr.forEach(alert);

 等价于:

1
2
3
4
vararr = [1, 2, 3, 4];
for(vark = 0, length = arr.length; k < length; k++) {
 alert(array[k]);
}

 forEach方法中的function回调有三个参数:第一个参数是遍历的数组内容,第二个参数是对应的数组索引,第三个参数是数组本身

因此:

  

1
2
3
4
5
[].forEach(function(value,index,array){
 
    //codesomething
 
  });

  

等价于:

 

1
2
3
4
5
$.each([],function(index,value,array){
 
   //codesomething
 
 })

  

写一个例子;

1
2
3
4
5
6
vararr = [1,2,3,4];
arr.forEach(function(value,index,array){
    array[index] == value;   //结果为true
    sum+=value;  
    });
console.log(sum);   //结果为 10

 

map:map即是 “映射”的意思 用法与 forEach 相似,用法即:

1
2
3
4
5
[].map(function(value,index,array){
 
  //code
 
})



示例代码:
<!DOCTYPE html><html><head><meta charset="utf-8"><title>菜鸟教程(runoob.com)</title></head><body><p>点击按钮列出数组的每个元素。</p><button onclick="numbers.forEach(myFunction)">点我</button><p id="demo"></p><script>demoP = document.getElementById("demo");var numbers = [4, 9, 16, 25];function myFunction(item, index) {    demoP.innerHTML = demoP.innerHTML + "index[" + index + "]: " + item + "<br>"; }</script></body></html>



原创粉丝点击