在here
它说这应该有效:
function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) return false;
}
return (element > 1);
}
console.log( [4, 5, 8, 12].find(isPrime) ); // 5
但我最终遇到了一个错误:
TypeError: undefined is not a function
这是为什么?
附言
我尽量不使用 underscorejs库,因为浏览器应该已经支持像 find()
这样的函数。
最佳答案
改用 polyfill,只需复制粘贴以下代码(来自 this 链接)以启用 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;
}
});
}
关于javascript - Array.prototype.find() 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24143604/