对象索引未达到预期的数组

时间:2019-04-16 06:19:27

标签: javascript arrays

我有一个数组

let arr = []

我正在向其中插入对象

let a = {name:"a", age: 20}
arr.push(a);

我正在检查以下具有相同对象分配给不同变量的索引

let b = {name:"a", age:20}

我尝试了

arr.indexOf(b);

我得到-1,我期望为0。

请指导我

4 个答案:

答案 0 :(得分:2)

JS按引用而不是按值进行对象比较(和搜索)。因此:要使foo == bar为真,foo和bar必须是同一对象,而不仅仅是具有相同属性和值的对象:

console.log({name:"a", age:20} == {name:"a", age:20});

因此,您需要使用诸如findIndex之类的东西,而不是indexOf。

let arr = [];
let a = {name:"a", age: 20};
arr.push(a);
let b = {name:"a", age:20}

const index = arr.findIndex(item => item.name === b.name && item.age === b.age);
console.log(index);

答案 1 :(得分:1)

这是因为对象是引用类型,变量ab指向两个不同的存储位置。因此a != b

let a = {name:"a", age: 20};
let b = {name:"a", age:20}
console.log(a == b);

答案 2 :(得分:0)

JavaScript默认情况下无法比较对象。请改用Array.findIndex

let arr = []

let a = {name:"a", age: 20}

arr.push(a);
let b = {name:"a", age:20}


console.log(arr.findIndex(elem => elem.name == b.name && elem.age == b.age));

答案 3 :(得分:0)

是的,因为Js通过使用引用而不是按值进行比较

let arr = [];

let a = {
  name: "a",
  age: 20
};
arr.push(a);

let b = {
  name: "a",
  age: 20
};

console.log(arr.indexOf(b));

let arr = [];

let a = {
  name: "a",
  age: 20
};
arr.push(a);

let b = a

console.log(arr.indexOf(b));