本文详细解析JavaScript数组的forEach()方法,介绍其调用数组每个元素的语法结构。重点说明callback回调函数与thisObject上下文参数的用法,并提供针对不支持该方法的旧版浏览器的Polyfill兼容代码实现,帮助开发者在不同环境中安全使用数组遍历功能。
forEach()方法语法与参数
JavaScript数组的forEach()方法用于遍历并调用数组中的每一个元素。其基本语法如下:
array.forEach(callback[, thisObject]);
该方法接受以下参数:
- callback:一个函数,用于对数组的每个元素进行测试或处理。
- thisObject:可选参数,指定回调函数执行时的this指向对象。
返回值:该方法没有返回值,即返回undefined。
兼容性与Polyfill实现
兼容性说明:
forEach()是JavaScript对ECMA-262标准的扩展,因此在某些旧版浏览器或非标准实现中可能不存在。为了确保兼容性,需要在代码顶部添加以下Polyfill脚本:
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