简体   繁体   English

javascript搜索数组以获取数组索引?

[英]javascript searching array for array indices?

Say I have: 说我有:

a=[[1,2],[3,4],[5,6]]

Is this wrong? 错了吗

a.indexOf([1,2])

Why -1? 为什么是-1?

Because [1,2] == [1,2] is false 因为[1,2] == [1,2]false

There is no equality of different instances of javascript objects. javascript对象的不同实例是不平等的。

From the MDN on == : MDN开始==

If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory. 如果两个操作数都是对象,则JavaScript将比较内部引用,当操作数引用内存中的同一对象时,内部引用相等。

You could build your own function to look for an array in an array, but in this case, as you would have to check all elements of the internal arrays (or build a hash code), this won't be fast. 您可以构建自己的函数以在数组中查找数组,但是在这种情况下,由于您必须检查内部数组的所有元素(或构建哈希码),因此这并不是很快。 You'd better avoid this kind of search. 您最好避免这种搜索。

You CANNOT compare ARRAYS in JAVASCRIPT! 不能在JAVASCRIPT比较数组!

JavaScript Arrays are essentially inherited from objects when you check equality condition the internal references of these tow objects are different which returns -1 despite if all the elements are same 当您检查相等性条件时,JavaScript数组本质上是从对象继承的,即使所有元素都相同,这些拖曳对象的内部引用也会返回-1

So when you call .indexOf it will compare arrays which will fail and hence you get -1 因此,当您调用.indexOf时,它将比较失败的数组,因此得到-1

You need to build your own function which deeply checks if the Array and its sub arrays are equal or you can use some libraries like _.js 您需要构建自己的函数,该函数可以深入检查Array及其子数组是否相等,或者可以使用_.js之类的库

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

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