此MDN頁[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find] 有這樣的填充工具:有人可以解釋這個Array.prototype.find()polyfill?
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
enumerable: false,
configurable: true,
writable: true,
value: function(predicate) {
if (this == null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
if (i in list) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
}
return undefined;
}
});
}
我的問題是什麼,這些線:
var list = Object(this);
var length = list.length >>> 0;
因爲this
絕對是一個數組(我們正在擴充Array.prototype )爲什麼要確保length
是數字,爲什麼使用Object()?
這種填充工具的麻煩是,它需要的Object.defineProperty方法,這在舊版瀏覽器中沒有實現查找功能。 – kennebec
如答案所示; '這個'不能保證是一個數組,你可以在下面的回答中看到'this'可以是什麼(如果你需要比TJ提供的更多信息):http://stackoverflow.com/a/16063711/1641941(under '這個變量') – HMR