试图防止将重复值添加到数组中. [英] Trying to prevent duplicate values to be added to an array.

查看:24
本文介绍了试图防止将重复值添加到数组中.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在单击事件上向数组添加重复值时,我的项目出现问题.

Having an issue with my project when it comes to adding a duplicate value to an array on a click event.

当我将点击的项目的值推送到数组 openedCards.push(card); 代码允许将多个项目值添加到数组中,从而使用单个项目创建匹配的值.

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.

我尝试像这样包装这段代码 if ($.inArray(card,openCards) < 0)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.

这里是这里是jsfiddle

推荐答案

使用 vanilla javascript,您可以执行以下操作:

With vanilla javascript you can do this like the following:

if (array.indexOf(value) === -1) array.push(value);

其中 array 是您不想重复的 value 数组.

Where array is your array of value's that you don't want duplicates of.

或者,您可以使用以下 es6 语法:

Or, you can use the following es6 syntax:

if (array.includes(value) === false) array.push(value);

这篇关于试图防止将重复值添加到数组中.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆