简体   繁体   English

Javascript indexOf没有按预期工作

[英]Javascript indexOf not working as expected

I am trying to test whether a value already exists in an array. 我试图测试一个值是否已存在于数组中。

In this case, the value of "node1" does not change. 在这种情况下,“node1”的值不会改变。 both arrays are identical. 两个阵列都是相同的。

However, the same node is added to the array twice, despite the indexOf(node1) test. 但是,尽管进行了indexOf(node1)测试,但同一节点会被添加到数组中两次。 http://jsfiddle.net/v9yxj5hm/2/ http://jsfiddle.net/v9yxj5hm/2/

var tree_rows = []; 

var node1 = ['Workplace','Revenue Overall',0];  
if (tree_rows.indexOf(node1) == -1){ tree_rows.push(node1); } 

node1 = ['Workplace','Revenue Overall',0]; 
if (tree_rows.indexOf(node1) == -1){ tree_rows.push(node1); } 

alert(tree_rows)

The .indexOf() method compares as if it were using the === strict equality operator. .indexOf()方法比较它使用===严格相等运算符。 No two distinct arrays are equal to each other under those conditions. 在这些条件下,没有两个不同的阵列彼此相等。

When you use array (or, for that matter, object) literal expressions to create objects, you get distinct individual objects. 当您使用数组(或者,就此而言,对象)文字表达式来创建对象时,您将获得不同的单个对象。 The fact that one literal expression looks exactly like another doesn't mean they share identity. 一个文字表达看起来与另一个完全相同的事实并不意味着它们共享身份。

The second use of declaration 第二次使用声明

node1 = ['Workplace','Revenue Overall',0];

when node1 already existed created a new entry in the lexical environment for node1. 当node1已经存在时,在node1的词法环境中创建了一个新条目。 As a result, the check for indexOf will not find a previous value for that entry. 因此,检查indexOf将找不到该条目的先前值。 This ends with node1 being placed in the array a second time. 这结束于node1第二次被放置在数组中。

You have to compare whether each item in node1 is in tree_rows . 您必须比较node1中的每个项目是否在tree_rows Maybe you want this? 也许你想要这个?

var tree_rows = []; 

var node1 = ['Workplace','Revenue Overall',0];  
for (i in node1) { if (tree_rows.indexOf(node1[i]) == -1){ tree_rows.push(node1[i]); }} 

node1 = ['Workplace','Revenue Overall',0]; 
for (i in node1) { if (tree_rows.indexOf(node1[i]) == -1){ tree_rows.push(node1[i]); }}

alert(tree_rows)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM