如何防止向 javascript 数组添加重复键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10757516/
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
how to prevent adding duplicate keys to a javascript array
提问by iamsar
I found a lot of related questions with answers talking about for...in loops and using hasOwnProperty but nothing I do works properly. All I want to do is check whether or not a key exists in an array and if not, add it.
我发现了很多相关的问题,答案都是关于 for...in 循环和使用 hasOwnProperty 但我所做的一切都无法正常工作。我想要做的就是检查数组中是否存在键,如果不存在,则添加它。
I start with an empty array then add keys as the page is scrubbed with jQuery.
我从一个空数组开始,然后在使用 jQuery 清理页面时添加键。
Initially, I hoped that something simple like the following would work: (using generic names)
最初,我希望像下面这样简单的东西会起作用:(使用通用名称)
if (!array[key])
array[key] = value;
No go. Followed it up with:
不行。跟进它:
for (var in array) {
if (!array.hasOwnProperty(var))
array[key] = value;
}
Also tried:
还试过:
if (array.hasOwnProperty(key) == false)
array[key] = value;
None of this has worked. Either nothing is pushed to the array or what I try is no better than simply declaring array[key] = value
Why is something so simple so difficult to do. Any ideas to make this work?
这些都没有奏效。要么没有任何内容被推送到数组中,要么我尝试array[key] = value
做的事情并不比简单地声明为什么这么简单的事情这么难做更好。有什么想法可以使这项工作?
回答by Sampson
Generally speaking, this is better accomplished with an object instead since JavaScript doesn't really have associative arrays:
一般来说,这最好用对象来完成,因为 JavaScript 并没有真正的关联数组:
var foo = { bar: 0 };
Then use in
to check for a key:
然后用于in
检查密钥:
if ( !( 'bar' in foo ) ) {
foo['bar'] = 42;
}
As was rightly pointed out in the comments below, this method is useful onlywhen your keys will be strings, or items that can be represented as strings (such as numbers).
正如在下面的评论中正确指出的那样,只有当您的键是字符串或可以表示为字符串的项目(例如数字)时,此方法才有用。
回答by Phrogz
var a = [1,2,3], b = [4,1,5,2];
b.forEach(function(value){
if (a.indexOf(value)==-1) a.push(value);
});
console.log(a);
// [1, 2, 3, 4, 5]
For more details read up on Array.indexOf
.
有关更多详细信息,请阅读Array.indexOf
。
If you want to rely on jQuery, instead use jQuery.inArray
:
如果您想依赖 jQuery,请改用jQuery.inArray
:
$.each(b,function(value){
if ($.inArray(value,a)==-1) a.push(value);
});
If all your values are simply and uniquely representable as strings, however, you should use an Object instead of an Array, for a potentially massivespeed increase (as described in the answer by @JonathanSampson).
但是,如果您的所有值都可以简单且唯一地表示为 strings,则您应该使用 Object 而不是 Array ,以获得潜在的巨大速度提升(如@JonathanSampson 的回答中所述)。
回答by Pavan
A better alternative is provided in ES6 using Sets. So, instead of declaring Arrays, it is recommended to use Sets if you need to have an array that shouldn't add duplicates.
ES6 中使用 Sets 提供了更好的替代方案。因此,如果您需要一个不应添加重复项的数组,则建议使用 Sets,而不是声明 Arrays。
var array = new Set();
array.add(1);
array.add(2);
array.add(3);
console.log(array);
// Prints: Set(3) {1, 2, 3}
array.add(2); // does not add any new element
console.log(array);
// Still Prints: Set(3) {1, 2, 3}
回答by Bruno Pinna
You can try this:
你可以试试这个:
var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
var uniqueNames = [];
$.each(names, function(i, el){
if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});
回答by Bruno Pinna
The logic is wrong. Consider this:
逻辑是错误的。考虑一下:
x = ["a","b","c"]
x[0] // "a"
x["0"] // "a"
0 in x // true
"0" in x // true
x.hasOwnProperty(0) // true
x.hasOwnProperty("0") // true
There is no reason to loop to check for key(or indicesfor arrays) existence. Now, valuesare a different story...
没有理由循环检查键(或数组的索引)是否存在。现在,价值观是另一回事了......
Happy coding
快乐编码
回答by abhiagNitk
function check (list){
var foundRepeatingValue = false;
var newList = [];
for(i=0;i<list.length;i++){
var thisValue = list[i];
if(i>0){
if(newList.indexOf(thisValue)>-1){
foundRepeatingValue = true;
console.log("getting repeated");
return true;
}
} newList.push(thisValue);
} return false;
}
var list1 = ["dse","dfg","dse"];
check(list1);
Output:
输出:
getting repeated
true