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
};
}

数组的方法之(Array.prototype.forEach() 方法)的更多相关文章

  1. 数组的方法之(Array.prototype.reduce() 方法)

    reduce函数 reduce() 方法对累加器和数组中的每个元素(从左到右)应用一个函数,将其减少为单个值. 对数组中的所有元素调用指定的回调函数.该回调函数的返回值为累积结果,并且此返回值在下一次 ...

  2. 数组的方法之(Array.prototype.filter() 方法)

    filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素.     注意: filter() 不会对空数组进行检测.     注意: filter() 不会改变原始 ...

  3. Array.prototype.forEach数组遍历

    forEach是Array新方法中最基本的一个,就是遍历,循环.先看以前是怎么遍历数组的 常用遍历 var arr = [1,2,3,4,5]; for(var i = 0; i < arr.l ...

  4. 终于解决了IE8不支持数组的indexOf方法,array的IndexOf方法

    /* 终于解决了IE8不支持数组的indexOf方法 */ if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (el ...

  5. Javascript数组Array的forEach方法

    Javascript数组Array的forEach扩展方法 forEach是最常用到的数组扩展方法之一,相当于参数化循环数组,它简单的在数组的每一个元素上应用传入的函数,这也意味着只有存在的元素会被访 ...

  6. Array.prototype.map()方法详解

    Array.prototype.map() 1 语法 const new_array = arr.map(callback[, thisArg]) 2 简单栗子 let arr = [1, 5, 10 ...

  7. 利用Array Prototype的方法来实现对dom集合的筛选、indexOf、map等功能

    <!DOCTYPE html><html> <head> <title>TODO supply a title</title> <me ...

  8. 数组Array和字符串String的indexOf方法,以及ES7(ES2016)中新增的Array.prototype.includes方法

    前言 我们在判断某一个字符是否存在于一个字符串中或者某一个值是否存在于一个数组中时,ES7之前我们需要使用indexOf,ES7引入了新的方法includes 语法 数组:Array.inexOf(s ...

  9. Array.prototype.forEach()&&Array.prototype.map()

    https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach https ...

随机推荐

  1. C++:多线程002

    https://blog.csdn.net/morewindows/article/details/7442333 程序描述:主线程启动10个子线程并将表示子线程序号的变量地址作为参数传递给子线程.子 ...

  2. [JZOJ6011] 【NOIP2019模拟1.25A组】天天爱跑步

    题目 描述 题目大意 给你平面直角坐标系上的nnn个起点和nnn个终点,(x,y)(x,y)(x,y)每次只能走到(x,y+x)(x+y,y)(x,y−x)(x−y,y)(x,y+x)(x+y,y)( ...

  3. 廖雪峰Java14Java操作XML和JSON-2JSON-2处理JSON

    解析JSON JSR 353 API 常用的第三方库 * Jackson * gson * fastjson Jackson: 提供了读写JSON的API JSON和JavaBean可以互相转换 可食 ...

  4. 0821NOIP模拟测试赛后总结

    60分rank20.挂.完. 赛时状态 不是很好.老眼混花看错无数题目信息. 倒不是很困.尽管昨天晚上为了某个该死的s-h-s-j活动报告忙到了今天,但我不得不说车上的睡眠还是挺好的. 照例通读三道题 ...

  5. memcache课程---1、memcache介绍及安装(memcache作用)

    memcache课程---1.memcache介绍及安装(memcache作用) 一.总结 一句话总结: 减少对数据库的访问,因为数据库的访问比较花费时间 1.memcache为什么比操作数据库快的多 ...

  6. PHP如何打造一个高可用高性能的网站呢?

    https://blog.csdn.net/jwq101666/article/details/80162245 1. 说到高可用的话要提一下redis,用过的都知道redis是一个具备数据库特征的n ...

  7. Origin使用自定义函数拟合曲线函数

    (2019年2月19日注:这篇文章原先发在自己github那边的博客,时间是2016年10月28日) 最近应该是六叔的物化理论作业要交了吧,很多人问我六叔的作业里面有两道题要怎么进行图像函数的拟合.综 ...

  8. 转: Linux题目

    源地址:http://blog.csdn.net/zcsylj/article/details/6799639 一.填空题:1. 在Linux系统中,以 文件 方式访问设备 .2. Linux内核引导 ...

  9. HBase 表和Region

  10. Vue跳转相同路由不同参数,解决页面数据不自动刷新

    参考: https://www.cnblogs.com/ainyi/p/9340311.html https://blog.csdn.net/weixin_41888813/article/detai ...