检查是否在数组元素存在不通过它遍历 [英] Checking if element exists in array without iterating through it
问题描述
我的数组:
tempListArray = "[{"id":"12","value":false},{"id":"10","value":false},{"id":"9","value":false},{"id":"8","value":false}]";
要检查元素是否存在,我会做这样的:
To check if an element exists I would do this:
for (var i in tempListArray) {
//check flag
if (tempListArray[i].id == Id) {
flagExistsLoop = 1;
break;
}
}
反正是有,我可以检查是否存在一个ID,而无需通过整个数组循环。基本上,我很担心性能,如果说我有一个100个元素。
Is there anyway, I can check if an Id exists without looping through the whole array. Basically I am worried about performance if say I have a 100 elements.
感谢
推荐答案
没有,你可以不知道,如果没有遍历数组。
No, you can't know that without iterating the array.
但是,请注意为中...
循环是迭代阵列的好方法:
However, note for...in
loops are a bad way of iterating arrays:
- 有没有保证,它会遍历数组与秩序
- 这也将遍历(枚举)非数字自己的属性
- 这也将是迭代来自原型,即(枚举)的属性,在
Array.prototype
和Object.protoype $定义C $ C>。
- There is no warranty that it will iterate the array with order
- It will also iterate (enumerable) non-numeric own properties
- It will also iterate (enumerable) properties that come from the prototype, i.e., defined in
Array.prototype
andObject.protoype
.
我会用其中的一个:
-
为
循环用数字索引:
for (var i=0; i<tempListArray.length; ++i) {
if (tempListArray[i].id == Id) {
flagExistsLoop = 1;
break;
}
}
Array.prototype.some
(ECMAScript中5):
Array.prototype.some
(EcmaScript 5):
var flagExistsLoop = tempListArray.some(function(item) {
return item.id == Id;
});
请注意它可以比其他的慢,因为它要求在每一步的功能。
Note it may be slower than the other ones because it calls a function at each step.
为...
的环(ECMAScript中6):
for...of
loop (EcmaScript 6):
for (var item of tempListArray) {
if (item.id == Id) {
flagExistsLoop = 1;
break;
}
}
这篇关于检查是否在数组元素存在不通过它遍历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!