![](/img/trans.png)
[英]undefined is not a constructor in Mocha / Chai / Sinon on PhantomJS with Array.prototype.find
[英]Array.prototype.find() is undefined
在這里
它說這應該有效:
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,只需復制粘貼以下代碼(來自此鏈接)即可啟用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;
}
});
}
如上所述,Array.prototype.find 方法是為 ECMAScript 6 提出的實驗性功能。但是如果你想使用它,並且你想要一個短的 polyfill 來完成這項工作,你可以使用這個(來自 這里):
if (!Array.prototype.find) {
Array.prototype.find = function (callback, thisArg) {
"use strict";
var arr = this,
arrLen = arr.length,
i;
for (i = 0; i < arrLen; i += 1) {
if (callback.call(thisArg, arr[i], i, arr)) {
return arr[i];
}
}
return undefined;
};
}
除了.find(...)
,您還可以簡單地使用.filter(...)[0]
。 (對於 IE >= 9)
例子:
function isEven(x) { return x % 2 == 0; } console.log([3, 4, 5].find(isEven)); // 4 console.log([3, 4, 5].filter(isEven)[0]); // 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.