代码改变世界

Javascript array forEach()

2011-11-08 15:55  前端小鬼  阅读(771)  评论(0)    收藏  举报

正常情况下,我们知道IE6-IE8都不支持ECMAscript262标准的forEach方法。

不过足够可以利用原型来实现这个方法。思路就是让每个元素去去调用传入的函数参数。这时候就用到了call方法。这个方法还是很关键的。

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);

结果是:

[0] is 12
[1] is 5
[2] is 8
[3] is 130
[4] is 44

其实,蛮多新标准的方法,虽然IE6,IE7,IE8不太支持,但是,还是可以实现的。嗯