JavaScript 数组Array-forEach()方法
时间:2019-08-20 13:50:49 来源:igfitidea点击:
说明
Javascript array forEach()方法为数组中的每个元素调用一个函数。
语法
array.forEach(callback[, thisObject]);
参数明细
callback−用于测试数组中每个元素的函数。
传递给callback的参数有:
- value - 当前索引的值。
- index - 当前索引
- array - 数组
thisObject—执行回调时用作此对象的对象。
返回值
返回创建的数组。
兼容性
此方法是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);
}
};
}
示例 - JS遍历数组
var array = [2, 4, 8];
array.forEach(function () {
console.log(this);
});
// 2
// 4
// 8
示例 - 可以使用callback值进行进一步处理
var arr = [2, 4, 8];
arr.forEach(function (value, index, array) {
console.log(value, index, array);
});
// 2 0 [2, 4, 8]
// 4 1 [2, 4, 8]
// 8 2 [2, 4, 8]

