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

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

问题描述

我发现了很多相关的问题,并在循环中使用了hasOwnProperty来讨论for ...的答案,但是我没有做任何适当的工作.我要做的就是检查数组中是否存在键,如果不存在,请将其添加.

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更好地完成此操作,因为JavaScript确实没有关联数组:

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

var foo = { bar: 0 };

然后使用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).

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

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