考慮Array.prototype.every()功能,Array.prototype.every() - 獲取falsy價值元素
我怎麼能得到falsy元素?例如 -
function isBigEnough(element, index, array) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); // get the element "5" (falsy)
考慮Array.prototype.every()功能,Array.prototype.every() - 獲取falsy價值元素
我怎麼能得到falsy元素?例如 -
function isBigEnough(element, index, array) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); // get the element "5" (falsy)
你可以使用過濾器:如果你想堅持太大的功能,那麼你可以使用
function tooSmall(element){
return element < 10
}
[12, 5, 8, 130, 44].filter(tooSmall) // gives [5, 8]
[12, 5, 8, 130, 44].filter(tooSmall)[0] // gives the first element ie 5
:
function not(fn) {
return function(){
return !fn.apply({},arguments)
}
}
[12, 5, 8, 130, 44].filter(not(isBigEnough)) // [5, 8]
我想獲得保存過濾器檢查的第一個元素。 – URL87 2015-02-11 13:46:12
我與其他一致您想要使用過濾器的答案/評論。不過,我在另一方面以不同的方式解釋你的問題。我如何解釋你所要求的是,一旦你已經過濾到bigEnough
你怎麼能再過濾到而不是夠大。
一個答案,這是使用下劃線的_.difference
方法:
var entireArray = [12, 5, 8, 130, 44];
var bigEnoughVals = entireArray.filter(isBigEnough);
var tooSmallVals = _.difference(entireArray, bigEnoughVals);
function isBigEnough(element, index, array) {
return element >= 10;
}
你最好使用'Array.prototype.filter'。 – dfsq 2015-02-11 13:43:38