JavaScript/jQuery相当于LINQ Any()

dil*_*ert 56 javascript ienumerable foreach jquery any

是否有相当于IEnumerable.Any(Predicate<T>)JavaScript或jQuery?

我正在验证项目列表,并希望在检测到错误时提前中断.我可以使用它$.each,但我需要使用外部标志来查看该项是否实际找到:

var found = false;
$.each(array, function(i) {
    if (notValid(array[i])) {
        found = true;
    }
    return !found;
});
Run Code Online (Sandbox Code Playgroud)

什么是更好的方式?我不喜欢for在JavaScript数组中使用plain ,因为它遍历所有成员,而不仅仅是值.

Sea*_*ira 74

这些天你实际上可以使用Array.prototype.some(在ES5中推出)来获得相同的效果:

array.some(function(item) {
    return notValid(item);
});
Run Code Online (Sandbox Code Playgroud)

  • 快速摘要:`some()`对数组中的每个元素执行一次回调函数,直到找到一个回调返回true值的元素.如果找到这样的元素,`some()`会立即返回true.否则,`some()`返回false. (9认同)

Xio*_*ion 17

您可以使用is接受谓词的jQuery 函数变体:

$(array).is(function(index) {
    return notValid(this);
});
Run Code Online (Sandbox Code Playgroud)

  • 我认为当用于`array`时,你应该避免在`is`函数中使用`this`.因为你不会得到原始类型(因此使用"==="进行比较将失败).我会用`array [i]`代替.见:http://jsfiddle.net/BYjcu/3/ (4认同)

SLa*_*aks 3

你应该使用一个普通的for循环(不是for ... in),它只会遍历数组元素.

  • @SLaks,你误解了Simon_Weaver的评论!"你*可以*使用普通的for循环." 而不是"你*应该*......" (4认同)