javascript 或 jquery 中方法 .some() 的等效工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16270553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Working equivalent for method .some() in javascript or jquery?
提问by trogwar
Was looking for "equivalent for some method in javascript" and "return just one value if is in array", but saw only the answers to the way in which to determine the type of variables or too many unnecessary.
正在寻找“等效于 javascript 中的某些方法”和“如果在数组中则只返回一个值”,但只看到了确定变量类型或太多不必要的方式的答案。
I bypass all inputs in html and i want something like this:
我绕过了 html 中的所有输入,我想要这样的东西:
$('#goodsFilter')
.find('input[type="number"]')
.some(function(i,el){
return (isNumber($(el).val())) ? 1 : 0;
});
But it throws an error:
但它抛出一个错误:
"TypeError: 'undefined' is not a function" (eg. Safari 6.0.4).
“TypeError: 'undefined' is not a function”(例如 Safari 6.0.4)。
UPD:Error comes from the last line, yeah, where });
.
isNumber:
UPD:错误来自最后一行,是的,在哪里});
。是编号:
function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); }
This should check for the presence of each input information, and, if at least one of them is not empty, return 1, otherwise 0. How can I replace it to work in most modern browsers?
这应该检查每个输入信息是否存在,如果其中至少一个不为空,则返回 1,否则返回 0。如何替换它以在大多数现代浏览器中工作?
UPD:Problem was solved. I'm a little confused in choosing the answer. The code of @RobG implementation of .some()
is more understandable for beginners (and I am) so I switched my vote.
UPD:问题已解决。我在选择答案时有点困惑。@RobG 实现的代码.some()
对于初学者(我也是)来说更容易理解,所以我改变了我的投票方式。
回答by Alex D
For anyone else who comes to this thread, you can use some()
on a jQuery object this way:
对于来到此线程的任何其他人,您可以通过some()
以下方式在 jQuery 对象上使用:
$.makeArray($(...)).some(function(x) { ... })
jQuery.makeArray()
converts the jQuery object into an Array, so you can use some()
on it.
jQuery.makeArray()
将 jQuery 对象转换为数组,以便您可以some()
在其上使用。
回答by RobG
Array.prototype.somereturns true or false, so you can do:
Array.prototype.some返回 true 或 false,因此您可以执行以下操作:
.some(function(el){
return !isNaN(el.value);
}
You don't say where the error comes from, is it from the call to isNumber?
你没有说错误来自哪里,是来自对isNumber的调用吗?
Edit
编辑
Ah, so your issue is with some.
啊,所以你的问题是一些.
If you want a jQuery somemethod, then it should at least mimic the built–in ECMAScript some, which takes two arguments: a callback function and an optional thisargument.
如果你想要一个 jQuery some方法,那么它至少应该模仿内置的 ECMAScript some,它有两个参数:一个回调函数和一个可选的this参数。
The callback function should take three arguments: the value, the index (optional) and an optional value to use as the thisargument. It should access the numeric members in ascending order and only visit members that actually exist.
回调函数应采用三个参数:值、索引(可选)和用作this参数的可选值。它应该按升序访问数字成员,并且只访问实际存在的成员。
So it should be something like (noting that jQuery.fn === jQuery.prototype):
所以它应该是这样的(注意 jQuery.fn === jQuery.prototype):
jQuery.fn.some = function(fn, thisArg) {
var result;
for (var i=0, iLen = this.length; i<iLen; i++) {
if (this.hasOwnProperty(i)) {
if (typeof thisArg == 'undefined') {
result = fn(this[i], i, this);
} else {
result = fn.call(thisArg, this[i], i, this);
}
if (result) return true;
}
}
return false;
}
So if you want now you can do:
所以如果你现在想要,你可以这样做:
var result = $('#goodsFilter')
.find('input[type="number"]')
.some(function(el) {
return isNumber(el.value);
})? 1 : 0;
or you can do either of the following to coerce trueto 1 and falseto 0:
或者您可以执行以下任一操作来将true强制为 1,将false强制为 0:
var result = Number($('#goodsFilter')
.find('input[type="number"]')
.some(function(el) {
return isNumber(el.value);
}));
or
或者
var result = +($('#goodsFilter')
.find('input[type="number"]')
.some(function(el) {
return isNumber(el.value);
}));
The above is only lightly tested, the optional thisArgparameter might be redundant.
以上只是轻微测试,可选的thisArg参数可能是多余的。
回答by xdazz
You could use the .filter
method, and then check the length.
您可以使用该.filter
方法,然后检查长度。
$('#goodsFilter')
.find('input[type="number"]')
.filter(function(i,el){ return isNumber($(el).val())); })
.length > 0
回答by diego nunes
. . In the most basic version, you can just create a "some" function:
. . 在最基本的版本中,您只需创建一个“一些”函数:
function eSome(arr, f) { var i = 0, n = arr.length;
for (;i<n;i++) { if (!i in arr) { continue }
if (f(i, arr[i])) { return true; }
} return false;
}
var list = [0, 1, 2, 3, 4, 5];
var testFunction = function (i, e) { return e === 2; };
console.log(eSome(list, testFunction));
//returns true and the loop ran only for the necessary three times.
. . If you want to chain the .some
call in a jQuery object, you can add it as a jQuery function as well, using something like this (now tested and fixed) example:
. . 如果你想.some
在一个 jQuery 对象中链接调用,你也可以将它添加为一个 jQuery 函数,使用这样的东西(现已测试和修复)示例:
jQuery.fn.some = function (f) { var i = 0, n = this.length;
for (;i<n;i++) { if (!i in this) { continue }
if (f(i, this[i])) { return true; }
}
return false;
}
$('.a').some(function (i, el) { return ($(el).text() == 'weeee!'); });
. . As @RobG pointed out in the comments, the native Array.prototype.some
implementation calls your callback with a different set of parameters. I'm following the OP's sample code, but you can mimic the ECMA implementation's parameter with if (f(this[i], i, this)) { return true; }
inside the loop.
. . 正如@RobG 在评论中指出的那样,本机Array.prototype.some
实现使用一组不同的参数调用您的回调。我正在关注 OP 的示例代码,但您可以if (f(this[i], i, this)) { return true; }
在循环内部模拟 ECMA 实现的参数。
. . You can also shim it on Array.prototype.some
, but I strongly advise against any direct modifications to the built-in prototypes.
. . 您也可以将其添加到 上Array.prototype.some
,但我强烈建议不要对内置原型进行任何直接修改。
回答by Dyson Lu
$(...).is(function)
should work too. The jQuery APIdocumentation states (emphasis mine):
$(...).is(function)
也应该工作。在jQuery的API文档状态(重点煤矿):
Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
根据选择器、元素或 jQuery 对象检查当前匹配的一组元素,如果这些元素中至少有一个与给定的参数匹配,则返回 true。
So using the example in the question, we would have something like:
因此,使用问题中的示例,我们将得到以下内容:
var result = $('#goodsFilter')
.find('input[type="number"]')
.is(function(idx, el) {
return isNumber(el.value);
})? 1 : 0;
回答by Carmine Tambascia
Implementation in Vanilla Javascript( with arrow syntax)
在 Vanilla Javascript 中实现(使用箭头语法)
function some(arr,callback){
for(let i=0;i<arr.length;i++){
if(callback(arr[i],i,arr)){
return true;
}
}
return false;
}
some use:
一些用途:
check if an array has an even number:
检查数组是否有偶数:
function hasEvenNum(arr){
return arr.some(value=>{
return value % 2 === 0;
});
}