zoukankan      html  css  js  c++  java
  • JS中map和foreach的区别以及some和every的用法

    一、原生JS forEach()和map()遍历

    共同点:

        1.都是循环遍历数组中的每一项。

        2.forEach() 和 map() 里面每一次执行匿名函数都支持3个参数:数组中的当前项item,当前项的索引index,原始数组input。

        3.匿名函数中的this都是指Window。

        4.只能遍历数组。

    1.forEach()

       没有返回值。
    
    arr[].forEach(function(value,index,array){
    
      //do something
    
    })
    • 参数:value数组中的当前项, index当前项的索引, array原始数组;
    • 数组中有几项,那么传递进去的匿名回调函数就需要执行几次;
    • 理论上这个方法是没有返回值的,仅仅是遍历数组中的每一项,不对原来数组进行修改;但是可以自己通过数组的索引来修改原来的数组;
    [javascript] view plain copy
     
    var ary = [12,23,24,42,1];  
    var res = ary.forEach(function (item,index,input) {  
           input[index] = item*10;  
    })  
    console.log(res);//--> undefined;  
    console.log(ary);//--> 通过数组索引改变了原数组;  


    2.map() 

    有返回值,可以return 出来。

    arr[].map(function(value,index,array){

      //do something

      return XXX

    })

    • 参数:value数组中的当前项,index当前项的索引,array原始数组;
    • 区别:map的回调函数中支持return返回值;return的是啥,相当于把数组中的这一项变为啥(并不影响原来的数组,只是相当于把原数组克隆一份,把克隆的这一份的数组中的对应项改变了);
    [javascript] view plain copy
     
    var ary = [12,23,24,42,1];  
    var res = ary.map(function (item,index,input) {  
        return item*10;  
    })  
    console.log(res);//-->[120,230,240,420,10];  原数组拷贝了一份,并进行了修改
    console.log(ary);//-->[12,23,24,42,1];  原数组并未发生变化

    every()与some()方法都是JS中数组的迭代方法。

    • every()是对数组中每一项运行给定函数,如果该函数对每一项返回true,则返回true。
    • some()是对数组中每一项运行给定函数,如果该函数对任一项返回true,则返回true。
    var arr = [ 1, 2, 3, 4, 5, 6 ]; 
    
    console.log( arr.some( function( item, index, array ){ 
        console.log( 'item=' + item + ',index='+index+',array='+array ); 
        return item > 3; 
    })); 
    
    console.log( arr.every( function( item, index, array ){ 
        console.log( 'item=' + item + ',index='+index+',array='+array ); 
        return item > 3; 
    }));

    运行结果: 
    这里写图片描述

    some一直在找符合条件的值,一旦找到,则不会继续迭代下去。 
    every从迭代开始,一旦有一个不符合条件,则不会继续迭代下去。

  • 相关阅读:
    第三次作业
    Mysql show variables系统变量详解
    利用正则检测文中敏感词并标红
    Android 连接大疆SDK
    Android 热修复方案Tinker
    Hander消息机制
    .net MemCache 入门到简单使用链接汇总
    用socket连接pop3服务器遇到的小问题
    我是如何取得Reflector的真实程序的
    google卫星地图的url计算
  • 原文地址:https://www.cnblogs.com/xiaozhumaopao/p/10231501.html
Copyright © 2011-2022 走看看