English 中文(简体)
如何防止将重复的密钥添加到 Javastramp 数组中
原标题:how to prevent adding duplicate keys to a javascript array

我发现很多相关问题的答案 都在谈论... 循环和使用 hasOwnProperty, 但我没有做任何正确的工作。 我只想检查一个数组中是否存在一个密钥, 如果不是的话, 添加它 。

我以空数组开始, 然后添加键, 因为页面用 jQuery 来擦除 。

起初,我希望像以下这样简单的东西能奏效:(使用通用名称)

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;

这一切都行不通。 要么没有任何东西被推到数组, 要么我尝试的东西比简单地宣布 < code> array[ key] = value = value 来得更好。 为什么这么简单的东西就很难做。 做这个工作有什么想法吗?

最佳回答

一般而言,用一个对象比用一个对象更能做到这一点,因为JavaScript实际上没有连带阵列:

var foo = { bar: 0 };

然后使用 in 来检查密钥 :

if ( !(  bar  in foo ) ) {
    foo[ bar ] = 42;
}

正如以下评论中正确指出的那样,当您的密钥是字符串或可以作为字符串(如数字)表示的项目时,该方法“仅 是有用的。

问题回答

ES6 使用 Sets 提供了更好的替代方法。 因此, 与其申报矩阵, 不如在需要设置一个数组时使用该数组, 该数组应该不添加重复数组 。

var array = new Set();
array.add(1);
array.add(2);
array.add(3);

console.log(array);
// Prints: Set(3) {1, 2, 3}

array.add(2); // does not add any new element

console.log(array);
// Still Prints: Set(3) {1, 2, 3}

在这里,一个简单的方法 使用分散。

本代码将提供重复的复制件 :

let colors = [ red ,  orange ,  yellow ];
let moreColors = [ orange ,  green ];

// uh oh! this gives us  orange  twice
let mergedColors = [...colors, ...moreColors];

这样您就可以在合并数组的同时过滤并删除它们。

let mergedColors = [...colors, ...moreColors.filter(c => !colors.includes(c)) ];

逻辑是错误的。考虑一下:

x = ["a","b","c"]
x[0]     // "a"
x["0"]   // "a"
0 in x   // true
"0" in x // true
x.hasOwnProperty(0)   // true
x.hasOwnProperty("0") // true

没有理由循环检查 < em> keys < / em > (或 < em>indices 表示数组) 的存在。 现在, < em > values 是一个不同的故事...

快乐的编码

function check (list){
    var foundRepeatingValue = false;
    var newList = [];
    for(i=0;i<list.length;i++){
        var thisValue = list[i];
        if(i>0){
            if(newList.indexOf(thisValue)>-1){
                foundRepeatingValue = true;
                console.log("getting repeated");
                return true;
            }
       } newList.push(thisValue);
    } return false;
}

var list1 = ["dse","dfg","dse"];
check(list1);

产出:

getting repeated
true

let x = "farceus";
let y = "character";

const commonCharacters = function (string1, string2) {
  let duplicateCharacter = "";
  for (let i = 0; i < string1.length; i += 1) {
    if (duplicateCharacter.indexOf(string1[i]) === -1) {
      if (string2.indexOf(string1[i]) !== -1) {
        duplicateCharacter += string1[i];
      }
    }
  }
  return [...duplicateCharacter];
};


console.log(commonCharacters(x, y));




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签