zoukankan      html  css  js  c++  java
  • for循环,foreach, map,reduce用法对比+for in,for of

    for不做赘述,相当简单;

    foreach方法

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

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

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

    map() :

    map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

    map() 方法按照原始数组元素顺序依次处理元素。

    注意: map() 不会对空数组进行检测。

    注意: map() 不会改变原始数组。

    array.map(function(currentValue,index,arr), thisValue)

    由以上可见:foreach, map参数是完全相同的

    reduce() :

    reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值并返回。

    reduce() 可以作为一个高阶函数,用于函数的 compose。

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

    array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

    for in;for of:

    for in

    用for in的方遍历数组

        for(let index in array) {  
            console.log(index,array[index]);  
        };

    用for in不仅可以对数组,也可以对enumerable对象操作

    var A = {a:1,b:2,c:3,d:"hello world"};  
    for(let k in A) {  
        console.log(k,A[k]);  
    } 

    for of

    在ES6中,增加了一个for of循环,使用起来很简单

    for(let v of array) {  
        console.log(v);  
    }; 
     
    let s = "helloabc"; 
    for(let c of s) {  
        console.log(c); 
    }

    总结来说:for in总是得到对像的key或数组,字符串的下标,而for of和forEach一样,是直接得到值
    for of不能对象用

  • 相关阅读:
    MVVM
    vue-cli初始化项目2.x|3.x
    逻辑覆盖
    white box白盒测试
    black box黑盒测试
    总结回顾js arr的常见方法以及相关的使用场景(一)
    js 原生功底 (一)
    markdown 语法总结(一)
    阿里一面,面试官想看到的究竟是什么,带你揭秘!!!!
    关于Axios 源码你想了解的 在这儿
  • 原文地址:https://www.cnblogs.com/wangtong111/p/11223351.html
Copyright © 2011-2022 走看看