zoukankan      html  css  js  c++  java
  • 【转】浅谈JavaScript中forEach与each

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

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

    等价于:

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

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

    因此:

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

    等价于:

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

    写一个例子;

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

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

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

    参考文档:

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

  • 相关阅读:
    winsows10 小技巧
    数组与智能指针
    卸载 VS2015
    Effective C++
    修改 git commit 的信息
    线程管理
    并发编程简介
    个别算法详解
    git 删除某个中间提交版本
    git 查看某一行代码的修改历史
  • 原文地址:https://www.cnblogs.com/gudi/p/8031205.html
Copyright © 2011-2022 走看看