Array.prototype.find() Is Undefined
In here it says that this should work: function isPrime(element, index, array) { var start = 2; while (start <= Math.sqrt(element)) { if (element % start++ <
Solution 1:
Use the polyfill instead, just copy-paste the following code (from this link) to enable the find
method:
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
enumerable: false,
configurable: true,
writable: true,
value: function(predicate) {
if (this == null) {
thrownewTypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
thrownewTypeError('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;
}
}
}
returnundefined;
}
});
}
Solution 2:
Instead of .find(...)
, you also can simply use .filter(...)[0]
. (For IE >= 9)
Example:
functionisEven(x) {
return x % 2 == 0;
}
console.log([3, 4, 5].find(isEven)); // 4console.log([3, 4, 5].filter(isEven)[0]); // 4
Reference: Array.prototype.filter()
Post a Comment for "Array.prototype.find() Is Undefined"