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