JavaScript的現代瀏覽器包括Array.forEach方法,可以讓你寫:MDC的forEach中的評論字符是什麼?
[1,2,3].foreach(function(num){ alert(num); }); // alerts 1, then 2, then 3
對於沒有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);
}
};
}
爲什麼此實現在函數定義中使用/ *和* /?即爲什麼寫function(fun /*, thisp*/)
而不是function(fun, thisp)
?
我唯一的問題是爲什麼他們這樣做。簡單地在函數頭中取消註釋thisp就會和'var thisp = arguments [1];'具有完全相同的效果,並且它會保存一行代碼。我錯過了什麼? – MooGoo 2010-08-10 17:37:15
@MooGoo:是的,在這種情況下,這種用法看起來並不令人滿意。它可以用來表明一個參數是可選的,但是這裏沒有代碼來處理它;如果您不提供參數,則該值將是未定義的。也許這就是預期的行爲,但代碼中沒有任何暗示。 – Guffa 2010-08-10 17:57:03