如何防止向 javascript 数组添加重复键 [英] how to prevent adding duplicate keys to a javascript array

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

问题描述

我发现了很多相关的问题,答案都是关于 for...in 循环和使用 hasOwnProperty 但我所做的一切都无法正常工作.我想要做的就是检查数组中是否存在某个键,如果不存在,则添加它.

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.

我从一个空数组开始,然后在使用 jQuery 清理页面时添加键.

I start with an empty array then add keys as the page is scrubbed with jQuery.

最初,我希望像下面这样简单的东西会起作用:(使用通用名称)

Initially, I hoped that something simple like the following would work: (using generic names)

if (!array[key])
   array[key] = value;

不行.跟进:

for (var in array) {
   if (!array.hasOwnProperty(var))
      array[key] = value;
}

也试过了:

if (array.hasOwnProperty(key) == false)
   array[key] = value;

这些都没有奏效.要么没有任何东西被推送到数组中,要么我尝试做的事情并不比简单地声明 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?

推荐答案

一般来说,这最好用对象来完成,因为 JavaScript 并没有真正的关联数组:

Generally speaking, this is better accomplished with an object instead since JavaScript doesn't really have associative arrays:

var foo = { bar: 0 };

然后使用 in 检查密钥:

Then use in to check for a key:

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).

这篇关于如何防止向 javascript 数组添加重复键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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