什么是Jquery中的prototype.any?

Can*_*Can 15 jquery prototypejs

我们.any在Prototype中调用了一个函数.我希望在Jquery中也一样.

我的Prototype代码是:

 if (item_name == '' || $R(1,ind).any(function(i){return($F("bill_details_"+i+"_narration") == item_name)})) {
     alert("This item already added.");
 }
Run Code Online (Sandbox Code Playgroud)

我想使用Jquery执行Equivalent函数.

请帮我实现所需的输出.提前致谢..

jan*_*mon 23

对于IE 9+,它内置于:

some()方法测试数组中的某个元素是否通过了由提供的函数实现的测试.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/some

[2, 4, 6, 8, 10].some(function(n) { return n > 5; });
// -> true (the iterator will return true on 6)
Run Code Online (Sandbox Code Playgroud)

对于IE 8及以下版本:

原型任何

[2, 4, 6, 8, 10].any(function(n) { return n > 5; });
// -> true (the iterator will return true on 6)
Run Code Online (Sandbox Code Playgroud)

你可以使用jQuery.grep:

jQuery.grep([2, 4, 6, 8, 10], function(n) { return n > 5; }).length > 0;
// -> true (as grep returns [6, 8, 10])
Run Code Online (Sandbox Code Playgroud)

下划线 _.any_.some

_.any([2, 4, 6, 8, 10], function(n) { return n > 5; });
// -> true (the iterator will return true on 6)
Run Code Online (Sandbox Code Playgroud)

  • 至于性能,要小心.任何人应该停止照看第一次出现,而.grep将遍历整个数组. (4认同)

Aln*_*tak 5

ES5有一个内置函数Array.prototype.some,用于测试数组中的任何元素是否与谓词函数匹配,并在找到匹配元素后立即停止迭代.

.some(function(el) {
    return el.value === item_name;
});
Run Code Online (Sandbox Code Playgroud)

然后你的问题变成了创建所需元素的数组之一,这比在Prototype中更难,因为jQuery中没有"范围"运算符.幸运的是$.map迭代空元素,即使内置Array.prototype.map不是这样你可以使用new Array(ind):

var found = $.map(new Array(ind), function(_, x) {
    return "bill_details_" + (x + 1) + "_narration";
}).some(function(id) {
    var el = document.getElementById(id);
    return el && (el.value === item_name);
});
Run Code Online (Sandbox Code Playgroud)

上面的链接包含.some旧版浏览器的垫片.