Javascript 试图防止将重复值添加到数组中。
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46700862/
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
Trying to prevent duplicate values to be added to an array.
提问by logikevcoder
Having an issue with my project when it comes to adding a duplicate value to an array on a click event.
在单击事件上向数组添加重复值时,我的项目出现问题。
when I push the clicked item's value to the array openedCards.push(card);the code allows for multiple item values to be added to the array thus creating a matched value with a single item.
当我将单击的项目的值推送到数组时openedCards.push(card);,代码允许将多个项目值添加到数组中,从而使用单个项目创建匹配的值。
I have tried wrapping this code like so if ($.inArray(card, openedCards) < 0)openedCards.push(card);i see that the match class is no longer being added to matching pairs, or any values for that matter.
我试过像这样包装这段代码,所以if ($.inArray(card, openedCards) < 0)openedCards.push(card);我看到匹配类不再被添加到匹配对中,或者任何与此相关的值。
here is the Here is the jsfiddle
这里是这里是的jsfiddle
回答by J Livengood
With vanilla javascript you can do this like the following:
使用 vanilla javascript,您可以执行以下操作:
if (array.indexOf(value) === -1) array.push(value);
Where arrayis your array of value's that you don't want duplicates of.
array您value不想重复的 's数组在哪里。
Or, you can use the following es6 syntax:
或者,您可以使用以下 es6 语法:
if (array.includes(value) === false) array.push(value);
回答by KnightFox
I think you are running into issues with using object reference vs value
我认为您在使用对象引用与值时遇到了问题
While obj and obj2 have same value for underlying properties, they both return different values to $.inArray
虽然 obj 和 obj2 具有相同的底层属性值,但它们都向 $.inArray 返回不同的值
arr = [];
obj = {}; obj.A = 2;
arr.push(obj);
obj2 = {}; obj2.A = 2;
console.log($.inArray(obj, arr)); // 0
console.log($.inArray(obj2, arr)); // -1
In this case, I would recommend using some other property of card to check for availability within the array
在这种情况下,我建议使用卡的其他一些属性来检查阵列中的可用性
function containsCard(card, list) {?
return list.some(function(elem) {
return elem.A === card.A
})
}
arr = [];
obj = {}; obj.A = 2;
arr.push(obj);
obj2 = {}; obj2.A = 2;
console.log(containsCard(obj, arr)); // true
console.log(containsCard(obj2, arr)); // true
回答by StackSlave
You can just use $.inArray(), like:
您可以使用$.inArray(),例如:
if(!$.inArray(value, array))array.push(value);

