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.
我发现很多相关的问题都是关于……在循环和使用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为什么这么简单的事情这么难做。有什么好办法吗?
5 个解决方案
#1
32
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 only when your keys will be strings, or items that can be represented as strings (such as numbers).
正如下面注释中正确指出的,此方法仅在键是字符串或可以表示为字符串(如数字)的项时才有用。
#2
23
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 massive speed increase (as described in the answer by @JonathanSampson).
如果所有的值都简单且唯一地表示为字符串,那么您应该使用对象而不是数组,以实现潜在的巨大速度增长(如@JonathanSampson在回答中描述的那样)。
#3
0
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 indices for arrays) existence. Now, values are a different story...
没有理由循环检查键(或数组的索引)是否存在。现在,价值观是一个不同的故事……
Happy coding
快乐的编码
#4
0
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
#5
0
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);
});
Easiest way to find duplicate values in a JavaScript array
在JavaScript数组中查找重复值的最简单方法
#1
32
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 only when your keys will be strings, or items that can be represented as strings (such as numbers).
正如下面注释中正确指出的,此方法仅在键是字符串或可以表示为字符串(如数字)的项时才有用。
#2
23
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 massive speed increase (as described in the answer by @JonathanSampson).
如果所有的值都简单且唯一地表示为字符串,那么您应该使用对象而不是数组,以实现潜在的巨大速度增长(如@JonathanSampson在回答中描述的那样)。
#3
0
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 indices for arrays) existence. Now, values are a different story...
没有理由循环检查键(或数组的索引)是否存在。现在,价值观是一个不同的故事……
Happy coding
快乐的编码
#4
0
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
#5
0
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);
});
Easiest way to find duplicate values in a JavaScript array
在JavaScript数组中查找重复值的最简单方法