现代浏览器中的 JavaScript 包含 Array.forEach 方法,可让您编写以下内容:
[1,2,3].foreach(function(num){ alert(num); }); // alerts 1, then 2, then 3
对于 Array 原型(prototype)上没有 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)
?
最佳答案
因为这是一条评论。
function(fun/*, thisp*/)
与 function(fun)
相同。函数头中没有第二个参数。
在函数中间,您可以看到变量 thisp
被声明,并分配了第二个参数的值。函数定义中的注释只是指出您可以使用两个参数调用该函数,尽管这两个参数没有在函数头中定义。
关于javascript - MDC 的 forEach 中的注释字符有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3451394/