in questa pagina MDN [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find] c'è questa polyfill:qualcuno può spiegare questo polyray di array.prototype.find()?
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;
}
});
}
La mia domanda è che cosa sono queste righe per:
var list = Object(this);
var length = list.length >>> 0;
dal this
è sicuramente una matrice (stiamo aumentando Array.prototype) quindi, perché assicurarsi che length
sia numerico e perché viene utilizzato Object()?
il problema con questo polyfill è che richiede la Metodo Object.defineProperty, che non è disponibile nei browser meno recenti che non implementano find. – kennebec
Come risposta indicata; 'Questo non è garantito come array, puoi vedere nella seguente risposta che cosa può essere questo (se hai bisogno di più informazioni di TJ fornite): http://stackoverflow.com/a/16063711/1641941 (sotto 'questa variabile') – HMR