这个MDN页面[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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;
由于这绝对是一个数组(我们正在增强Array.prototype),所以为什么要确保length
是数字,为什么要使用Object()?