Javascript 数组 forEach() 方法
说明:
Javascript 数组 forEach() 方法为数组中的每个元素调用一个函数。
语法:
array.forEach(callback[, thisObject]);
参数详情如下:
-
回调:函数来测试数组的每个元素。
-
thisObject : 执行回调时用作 this 的对象。
返回值:
返回创建的数组。
兼容性:
此方法是对 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);
}
};
}
示例:
<html>
<head>
<title>JavaScript Array forEach Method</title>
</head>
<body>
<script type="text/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);
}
};
}
function printBr(element, index, array) {
document.write("<br />[" + index + "] is " + element );
}
[12, 5, 8, 130, 44].forEach(printBr);
</script>
</body>
</html>
这将产生以下结果:
[0] is 12
[1] is 5
[2] is 8
[3] is 130
[4] is 44
要更好地理解它,您可以Try it yourself。
SOURCE