JavaScript/jQuery 相当于 LINQ Any()
JavaScript 或 jQuery 中是否有等效的 IEnumerable.Any(Predicate
?
我正在验证项目列表,并且希望在检测到错误时尽早中断。我可以使用 $.each
来完成此操作,但我需要使用外部标志来查看是否确实找到了该项目:
var found = false;
$.each(array, function(i) {
if (notValid(array[i])) {
found = true;
}
return !found;
});
什么是更好的方法?我不喜欢将普通的 for
与 JavaScript 数组一起使用,因为它会迭代其所有成员,而不仅仅是值。
Is there an equivalent of IEnumerable.Any(Predicate<T>)
in JavaScript or jQuery?
I am validating a list of items, and want to break early if error is detected. I could do it using $.each
, but I need to use an external flag to see if the item was actually found:
var found = false;
$.each(array, function(i) {
if (notValid(array[i])) {
found = true;
}
return !found;
});
What would be a better way? I don't like using plain for
with JavaScript arrays because it iterates over all of its members, not just values.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
如今,您实际上可以使用
Array.prototype.some
(ES5 中指定)以获得相同的效果:
These days you could actually use
Array.prototype.some
(specced in ES5) to get the same effect:您可以使用 jQuery
is
函数的变体,它接受谓词:You could use variant of jQuery
is
function which accepts a predicate:西安的回答是正确的。扩展他的答案:
jQuery 的
.is(function)
与 .NET 的IEnumerable.Any(Predicate)
具有相同的行为。来自 http://docs.jquery.com/is:
Xion's answer is correct. To expand upon his answer:
jQuery's
.is(function)
has the same behavior as .NET'sIEnumerable.Any(Predicate<T>)
.From http://docs.jquery.com/is:
您应该使用普通的
for
循环(而不是for ... in
),它只会循环遍历数组元素。You should use an ordinary
for
loop (notfor ... in
), which will only loop through array elements.您可以使用 array.filter (IE 9+ 请参阅下面的链接了解更多详细信息)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
You might use array.filter (IE 9+ see link below for more detail)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
我建议您尝试 JavaScript
for in
循环。但是,请注意,其语法与 .netIEnumerable
的语法有很大不同。这是一个小的说明性代码示例。I would suggest that you try the JavaScript
for in
loop. However, be aware that the syntax is quite different than what you get with a .netIEnumerable
. Here is a small illustrative code sample.我建议您使用
$.grep()
方法。它非常接近IEnumerable.Any(Predicate)
:这里有一个工作示例:http://jsfiddle.net/ErickPetru/BYjcu/。
2021 更新
这个答案是在 10 多年前发布的,所以重要的是要强调这一点:
I suggest you to use the
$.grep()
method. It's very close toIEnumerable.Any(Predicate<T>)
:Here a working sample to you: http://jsfiddle.net/ErickPetru/BYjcu/.
2021 Update
This answer was posted more than 10 years ago, so it's important to highlight that:
死灵术。
如果你不能使用 array.some,你可以在 TypeScript 中创建你自己的函数:
它会转换为
用法:
Necromancing.
If you cannot use array.some, you can create your own function in TypeScript:
Which transpiles down to
Usage: