此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