简体   繁体   English

Javascript Array.indexOf()应用于对象数组时显示奇怪的行为

[英]Javascript Array.indexOf() shows strange behaviour when applied to array of objects

I have created the following code http://jsfiddle.net/EbCUx/ 我创建了以下代码http://jsfiddle.net/EbCUx/

var arr = [{a:1,b:2,c:3},{a:3,b:5,c:6}];
var a = arr[0];
alert(arr.indexOf(a));
var b = {a:1,b:2,c:3};
alert(arr.indexOf(b));

Why indexOf() returns -1 eventhough contents of a and b are same.. I know that a is a reference value ..Is that the cause...And can anybody explain me the exact reason? 尽管a和b的内容相同,为什么indexOf()返回-1。我知道a是一个参考值..是原因吗?有人可以向我解释确切的原因吗​​?

You are comparing 2 different objects that happen to have the same values inside, but they are still different objects from an equality perspective. 您正在比较内部恰好具有相同值的2个不同对象,但是从相等的角度来看,它们仍然是不同的对象。

Your original code: 您的原始代码:

<script>
    var arr = [{a:1,b:2,c:3},{a:3,b:5,c:6}];
    var a = arr[0];
    alert(arr.indexOf(a));
    var b = {a:1,b:2,c:3};
    alert(arr.indexOf(b));
</script>

An updated version that shows how to get a match on the comparison. 更新的版本显示了如何在比较中获得匹配。

<script>
    var b = {a:1,b:2,c:3};
    var arr = [b,{a:3,b:5,c:6}];
    var a = arr[0];
    alert(arr.indexOf(a));
    alert(arr.indexOf(b));
</script>

If you want to compare 2 different objects that happen to have the same values, you have to do so manually. 如果要比较两个具有相同值的不同对象,则必须手动进行比较。

From MDN : MDN

indexOf compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator). indexOf使用严格相等(===或三重相等运算符使用的相同方法)将searchElement与Array的元素进行比较。

Since no two objects are ever strictly equal, you can not use indexOf to search an array of objects, you must loop (or extend indexOf to loop if the elements of the array are objects) 由于没有两个对象严格相等,因此不能使用indexOf搜索对象数组,因此必须循环(如果数组的元素是对象,则必须循环使用indexOf进行循环)

Use this instead 改用这个

add this code: 添加此代码:

<script>
   Array.prototype.newIndexOf = function( item ) {
      var count = this.length;
      var j = 0;
      while (this[j++] !== item && j < count) {}
      return (j === count) ? -1 : j;
   }
</script>

indexOf is slow and no strict equal check. indexOf很慢,没有严格的相等检查。

http://jsperf.com/indexof-vs-equaling/2 http://jsperf.com/indexof-vs-equaling/2

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

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