【发布时间】:2010-08-10 16:54:48
【问题描述】:
现代浏览器中的 JavaScript 包含 Array.forEach 方法,可让您编写以下代码:
[1,2,3].foreach(function(num){ alert(num); }); // alerts 1, then 2, then 3
对于 Array 原型上没有 Array.forEach 的浏览器,MDC 提供了 an implementation 来做同样的事情:
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(fun /*, thisp*/) {
var len = this.length >>> 0;
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);
}
};
}
为什么这个实现在函数定义中使用 /* 和 */? IE。为什么写成function(fun /*, thisp*/) 而不是function(fun, thisp)?
【问题讨论】:
标签: javascript foreach