开发手册 欢迎您!
软件开发者资料库

JavaScript(JS) array.forEach(callback[, thisObject])

Array对象允许在一个变量中存储多个值。它存储相同类型元素的固定大小的顺序集合。数组用于存储数据集合,但将数组看作同一类型变量的集合通常更有用。本文主要介绍JavaScript(JS) array.forEach(callback[, thisObject]) 方法。

1、描述

JavaScript数组foreach()方法调用数组中每个元素的函数。

2、语法

它的语法如下:

array.forEach(callback[, thisObject]);

3、参数

  • callback:函数来测试每个元素。
  • thisObject:this对象在执行回调时使用。

4、返回值

返回创建的数组。

5、兼容性

此方法是ECMA-262标准的JavaScript扩展;因此,它可能不存在于标准的其他实施中。要使它工作,需要在脚本顶部添加以下代码。

if (!Array.prototype.forEach) {   Array.prototype.forEach = function(fun /*, thisp*/) {      var len = this.length;      if (typeof fun != "function")      throw new TypeError();            var thisp = arguments[1];      for (var i = 0; i < len; i++) {         if (i in this)         fun.call(thisp, this[i], i, this);      }   };}

6、使用示例

         JavaScript Array forEach Method                           

7、输出

[0] = 11[1] = 4[2] = 9[3] = 129[4] = 45