zoukankan      html  css  js  c++  java
  • 数组的方法之(Array.prototype.forEach() 方法)

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

    注意: 没有返回一个新数组 并且 没有返回值!

    应用场景:为一些相同的元素,绑定事件处理器!

    const arr = ['a', 'b', 'c'];
    
    arr.forEach(function(element) {
        console.log(element);
    });
    
    
    arr.forEach( element => console.log(element));

    语法

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

    • currentValue(当前值): 数组中正在处理的当前元素。
    • index(索引): 数组中正在处理的当前元素的索引。
    • array: forEach()方法正在操作的数组。
    • thisArg可选可选参数:当执行回调 函数时用作this的(参考对象)。

    返回值: undefined.

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

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

       forEach 遍历的范围第一次调用 callback 前就会确定。调用forEach 后添加数组中的项不会被 callback 访问到。如果已经存在的值改变,则传递给 callback 的值是 forEach 遍历到他们那一刻的值。已删除的项不会被遍历到。

       forEach() 为每个数组元素执行callback函数;不像map() 或者reduce() ,它总是返回 undefined值,并且不可链式调用。典型用例是在一个链的最后执行副作用。

    使用thisArg 

          function Counter() {
              this.sum = 0;
              this.count = 0;
          }
          Counter.prototype.add = function(array) {
              array.forEach((entry) => {
                  console.log(this);// Counter构造函数
                  this.sum += entry;
                  ++this.count;
              }, this);
          };
          var obj = new Counter();
          obj.add([1, 3, 5, 7]);
          console.log(obj.count); // 4 === (1+1+1+1)
          console.log(obj.sum); // 16 === (1+3+5+7)

    注意:如果使用箭头函数表达式传入函数参数,thisArg 参数会被忽略,因为箭头函数在词法上绑定了this值。

    兼容旧环境

    if (!Array.prototype.forEach) {
      Array.prototype.forEach = function(callback, thisArg) {
        var T, k;
        if (this == null) {
          throw new TypeError(' this is null or not defined');
        }
        // 1. Let O be the result of calling toObject() passing the
        // |this| value as the argument.
        var O = Object(this);
        // 2. Let lenValue be the result of calling the Get() internal
        // method of O with the argument "length".
        // 3. Let len be toUint32(lenValue).
        var len = O.length >>> 0;
    
        // 4. If isCallable(callback) is false, throw a TypeError exception. 
        // See: http://es5.github.com/#x9.11
        if (typeof callback !== "function") {
          throw new TypeError(callback + ' is not a function');
        }
    
        // 5. If thisArg was supplied, let T be thisArg; else let
        // T be undefined.
        if (arguments.length > 1) {
          T = thisArg;
        }
    
        // 6. Let k be 0
        k = 0;
    
        // 7. Repeat, while k < len
        while (k < len) {
    
          var kValue;
    
          // a. Let Pk be ToString(k).
          //    This is implicit for LHS operands of the in operator
          // b. Let kPresent be the result of calling the HasProperty
          //    internal method of O with argument Pk.
          //    This step can be combined with c
          // c. If kPresent is true, then
          if (k in O) {
            // i. Let kValue be the result of calling the Get internal
            // method of O with argument Pk.
            kValue = O[k];
            // ii. Call the Call internal method of callback with T as
            // the this value and argument list containing kValue, k, and O.
            callback.call(T, kValue, k, O);
          }
          // d. Increase k by 1.
          k++;
        }
        // 8. return undefined
      };
    }
  • 相关阅读:
    算法第二章上机实践报告
    算法第一章作业
    第7章学习小结 不使用STL-map过实践题:QQ帐户的申请与登陆
    第6章学习小结
    HDU
    HDU 2089 不要62(数位DP)
    char-2
    chart-7
    chart-6
    char-8
  • 原文地址:https://www.cnblogs.com/xuzhudong/p/8889643.html
Copyright © 2011-2022 走看看