zoukankan      html  css  js  c++  java
  • 关于数组的遍历forEach() 方法

    forEach() 方法对数组的每个元素执行一次提供的函数。

    复制代码
    let a = ['a', 'b', 'c'];
    
    a.forEach(function(element) {
        console.log(element);
    });
    
    // a
    // b
    // c
    复制代码

    语法:

    array.forEach(callback(currentValue, index, array){
        //do something
    }, this)
    
    array.forEach(callback[, thisArg])

    参数:

    callback为数组中每个元素执行的函数,该函数接收三个参数:

    currentValue(当前值)
    数组中正在处理的当前元素。
    index(索引)
    数组中正在处理的当前元素的索引。
    array
    forEach()方法正在操作的数组。

    thisArg可选可选参数。当执行回调 函数时用作this的值(参考对象)。

    描述:

    forEach 方法按升序为数组中含有效值的每一项执行一次callback 函数,那些已删除(使用delete方法等情况)或者未初始化的项将被跳过(但不包括那些值为 undefined 的项)(例如在稀疏数组上)。

    callback 函数会被依次传入三个参数:

    • 数组当前项的值
    • 数组当前项的索引
    • 数组对象本身

    如果给forEach传递了thisArg参数,当调用时,它将被传给callback 函数,作为它的this值。否则,将会传入 undefined 作为它的this值。callback函数最终可观察到this值,这取决于 函数观察到this的常用规则

    forEach 遍历的范围在第一次调用 callback 前就会确定。调用forEach 后添加到数组中的项不会被 callback 访问到。如果已经存在的值被改变,则传递给 callback 的值是 forEach 遍历到他们那一刻的值。已删除的项不会被遍历到。如果已访问的元素在迭代时被删除了(例如使用 shift()) ,之后的元素将被跳过 - 参见下面的示例。

    例子:

    复制代码
    function logArrayElements(element, index, array) {
        console.log("a[" + index + "] = " + element);
    }
    
    // 注意索引2被跳过了,因为在数组的这个位置没有项
    [2, 5, ,9].forEach(logArrayElements);
    
    // a[0] = 2
    // a[1] = 5
    // a[3] = 9
    
    [2, 5,"" ,9].forEach(logArrayElements);
    // a[0] = 2
    // a[1] = 5
    // a[2] = 
    // a[3] = 9
    
    [2, 5, undefined ,9].forEach(logArrayElements);
    // a[0] = 2
    // a[1] = 5
    // a[2] = undefined
    // a[3] = 9
    
    
    let xxx;
    // undefined
    
    [2, 5, xxx ,9].forEach(logArrayElements);
    // a[0] = 2
    // a[1] = 5
    // a[2] = undefined
    // a[3] = 9
    复制代码
    复制代码
    //从每个数组中的元素值中更新一个对象的属性:
    function Counter() { this.sum = 0; this.count = 0; } Counter.prototype.add = function(array) { array.forEach(function(entry) { this.sum += entry; ++this.count; }, this); //console.log(this); }; var obj = new Counter(); obj.add([1, 3, 5, 7]); obj.count; // 4 === (1+1+1+1) obj.sum; // 16 === (1+3+5+7)
    复制代码

    因为thisArg参数 (this) 传给了forEach(),每次调用时,它都被传给callback函数,作为它的this值。

  • 相关阅读:
    6.11 修饰符的适用范围
    5.10 对象与垃圾回收
    5.9 枚举类
    5.8 java 11增强的Lambda表达式
    5.7 内部类
    5.6 接口
    5.5 抽象类
    5.4 final修饰符
    5.3 类成员
    5.2 Object类中两个需要被重写的方法
  • 原文地址:https://www.cnblogs.com/mei123/p/8473331.html
Copyright © 2011-2022 走看看