JavaScript/jQuery 相当于 LINQ Any()

发布于 2024-11-06 12:25:05 字数 412 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

木格 2024-11-13 12:25:05

如今,您实际上可以使用 Array.prototype.some(ES5 中指定)以获得相同的效果:

array.some(function(item) {
    return notValid(item);
});

These days you could actually use Array.prototype.some (specced in ES5) to get the same effect:

array.some(function(item) {
    return notValid(item);
});
情绪操控生活 2024-11-13 12:25:05

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

$(array).is(function(index) {
    return notValid(this);
});

You could use variant of jQuery is function which accepts a predicate:

$(array).is(function(index) {
    return notValid(this);
});
太阳哥哥 2024-11-13 12:25:05

西安的回答是正确的。扩展他的答案:

jQuery 的 .is(function) 与 .NET 的 IEnumerable.Any(Predicate) 具有相同的行为。

来自 http://docs.jquery.com/is

根据表达式检查当前选择,如果选择的至少一个元素符合给定表达式,则返回 true。

Xion's answer is correct. To expand upon his answer:

jQuery's .is(function) has the same behavior as .NET's IEnumerable.Any(Predicate<T>).

From http://docs.jquery.com/is:

Checks the current selection against an expression and returns true, if at least one element of the selection fits the given expression.

無心 2024-11-13 12:25:05

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

You should use an ordinary for loop (not for ... in), which will only loop through array elements.

記憶穿過時間隧道 2024-11-13 12:25:05

您可以使用 array.filter (IE 9+ 请参阅下面的链接了解更多详细信息)

[].filter(function(){ return true|false ;}).length > 0;

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)

[].filter(function(){ return true|false ;}).length > 0;

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

冷月断魂刀 2024-11-13 12:25:05

我建议您尝试 JavaScript for in 循环。但是,请注意,其语法与 .net IEnumerable 的语法有很大不同。这是一个小的说明性代码示例。

var names = ['Alice','Bob','Charlie','David'];
for (x in names)
{
    var name = names[x];
    alert('Hello, ' + name);
}

var cards = { HoleCard: 'Ace of Spades', VisibleCard='Five of Hearts' };
for (x in cards)
{
    var position = x;
    var card = card[x];
    alert('I have a card: ' + position + ': ' + card);
}

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 .net IEnumerable. Here is a small illustrative code sample.

var names = ['Alice','Bob','Charlie','David'];
for (x in names)
{
    var name = names[x];
    alert('Hello, ' + name);
}

var cards = { HoleCard: 'Ace of Spades', VisibleCard='Five of Hearts' };
for (x in cards)
{
    var position = x;
    var card = card[x];
    alert('I have a card: ' + position + ': ' + card);
}
非要怀念 2024-11-13 12:25:05

我建议您使用 $.grep() 方法。它非常接近 IEnumerable.Any(Predicate)

$.grep(array, function(n, i) {
  return (n == 5);
});

这里有一个工作示例:http://jsfiddle.net/ErickPetru/BYjcu/

2021 更新

这个答案是在 10 多年前发布的,所以重要的是要强调这一点:

  1. 当它发布时,这是一个完全有意义的解决方案,因为 JavaScript 本身没有任何东西可以通过单个函数调用来解决这个问题那个时候;
  2. 原始问题具有 jQuery 标签,因此基于 jQuery 的答案不仅是预期的,而且是必须的。因为这个而投反对票根本没有意义。
  3. 从那时起,JavaScript 世界发生了很大的变化,所以如果您不喜欢 jQuery,请使用更新的解决方案!此处出于历史目的,并作为旧需求的参考,也许有人在使用遗留代码时仍然发现有用。

I suggest you to use the $.grep() method. It's very close to IEnumerable.Any(Predicate<T>):

$.grep(array, function(n, i) {
  return (n == 5);
});

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:

  1. When it was published, it was a solution that made total sense, since there was nothing native to JavaScript to solve this problem with a single function call at that time;
  2. The original question has the jQuery tag, so a jQuery-based answer is not only expected, it's a must. Down voting because of that doesn't makes sense at all.
  3. JavaScript world evolved a lot since then, so if you aren't stuck with jQuery, please use a more updated solution! This one is here for historical purposes, and to be kept as reference for old needs that maybe someone still find useful when working with legacy code.
月下伊人醉 2024-11-13 12:25:05

死灵术。
如果你不能使用 array.some,你可以在 TypeScript 中创建你自己的函数:

interface selectorCallback_t<TSource> 
{
    (item: TSource): boolean;
}


function Any<TSource>(source: TSource[], predicate: selectorCallback_t<TSource> )
{
    if (source == null)
        throw new Error("ArgumentNullException: source");
    if (predicate == null)
        throw new Error("ArgumentNullException: predicate");

    for (let i = 0; i < source.length; ++i)
    {
        if (predicate(source[i]))
            return true;
    }

    return false;
} // End Function Any

它会转换为

function Any(source, predicate) 
 {
    if (source == null)
        throw new Error("ArgumentNullException: source");
    if (predicate == null)
        throw new Error("ArgumentNullException: predicate");
    for (var i = 0; i < source.length; ++i) 
    {
        if (predicate(source[i]))
            return true;
    }
    return false;
}

用法:

var names = ['Alice','Bob','Charlie','David'];
Any(names, x => x === 'Alice');

Necromancing.
If you cannot use array.some, you can create your own function in TypeScript:

interface selectorCallback_t<TSource> 
{
    (item: TSource): boolean;
}


function Any<TSource>(source: TSource[], predicate: selectorCallback_t<TSource> )
{
    if (source == null)
        throw new Error("ArgumentNullException: source");
    if (predicate == null)
        throw new Error("ArgumentNullException: predicate");

    for (let i = 0; i < source.length; ++i)
    {
        if (predicate(source[i]))
            return true;
    }

    return false;
} // End Function Any

Which transpiles down to

function Any(source, predicate) 
 {
    if (source == null)
        throw new Error("ArgumentNullException: source");
    if (predicate == null)
        throw new Error("ArgumentNullException: predicate");
    for (var i = 0; i < source.length; ++i) 
    {
        if (predicate(source[i]))
            return true;
    }
    return false;
}

Usage:

var names = ['Alice','Bob','Charlie','David'];
Any(names, x => x === 'Alice');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文