Javascript Array.push() 和唯一项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36719477/
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
Array.push() and unique items
提问by Tomek Buszewski
I have a simple case of pushing unique values into array. It looks like this:
我有一个将唯一值推入数组的简单案例。它看起来像这样:
this.items = [];
add(item) {
if(this.items.indexOf(item) > -1) {
this.items.push(item);
console.log(this.items);
}
}
Seems pretty straight-forward, right? No, as it appears. It doesn't add any values. I am sure it's some kind of silly mistake on my side, but I can't seem to find it.
看起来很直接,对吧?不,正如它所显示的那样。它不会添加任何值。我确定这是我这边的某种愚蠢的错误,但我似乎无法找到它。
回答by JagsSparrow
Yep, it's a small mistake.
是的,这是一个小错误。
if(this.items.indexOf(item) === -1) {
this.items.push(item);
console.log(this.items);
}
回答by Sergey Zhigalov
回答by lachlan.p.jordan
try .includes()
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true
so something like
所以像
const array = [1, 3];
if (!array.includes(2))
array.push(2);
note the browser compatibility at the bottom of the page, however.
但是,请注意页面底部的浏览器兼容性。
回答by Vivek Kumar
I guess ES6 has set data structure, which you can use for unique entries
我猜 ES6 已经设置了数据结构,您可以将其用于唯一条目
回答by KitKit
回答by ManoDestra
Your logic is saying, "if this item exists already, then add it." It should be the opposite of that.
你的逻辑是,“如果这个项目已经存在,那就添加它。” 应该是相反的。
Change it to...
将其更改为...
if (this.items.indexOf(item) == -1) {
this.items.push(item);
}
回答by fdfey
You have to use === -1, if it equals to -1 i.e. item is not available in your array:
您必须使用 === -1,如果它等于 -1,即项目在您的数组中不可用:
this.items = [];
add(item) {
if(this.items.indexOf(item) === -1) {
this.items.push(item);
console.log(this.items);
}
}
回答by Martin Morawiec
var helper = {};
for(var i = 0; i < data.length; i++){
helper[data[i]] = 1; // Fill object
}
var result = Object.keys(helper); // Unique items
回答by Rohit Agrohia
Push always unique value in array
在数组中始终推送唯一值
ab = [
{"id":"1","val":"value1"},
{"id":"2","val":"value2"},
{"id":"3","val":"value3"}
];
var clickId = [];
var list = JSON.parse(ab);
$.each(list, function(index, value){
if(clickId.indexOf(value.id) < 0){
clickId.push(value.id);
}
});