简体   繁体   English

IndexOf 方法未按预期工作 JAVASCRIPT

[英]IndexOf method not working as expected JAVASCRIPT

nodesData=[
    {name:'name1'},
    {name:'name2'},
    {name:'name1'},
    {name:'name3'},
]

uniqData=[
    {name:'name1'}
    {name:'name2'}
    {name:'name3'}
]

for (let i = 0; i < nodesData.length; i += 2) {
  const currentSource = nodesData[i];
  const currentTarget = nodesData[i + 1];

  const currentData = {
    source: uniqData.indexOf(currentSource),
    target: uniqData.indexOf(currentTarget),
  };
}

So I've got two lists with objects.所以我有两个包含对象的列表。 First list is list with objects that contains names, and other list is list generated with function that I've made for removing duplicates.The problem is when I use for loop and loop through nodesData list only the first time I get only for source index of -1...why?第一个列表是包含名称的对象的列表,另一个列表是使用 function 生成的列表,我为删除重复项而制作。问题是当我使用 for 循环和遍历 nodesData 列表时,我第一次只获得源索引-1...为什么? and other indexOf work expected.和其他 indexOf 工作预期。

So the console.log would be:所以 console.log 将是:

source:-1, target:1

source:0, target:2

The objects in the array have differents references even if they looks like they are the same.数组中的对象具有不同的引用,即使它们看起来相同。 Basically:基本上:

 console.log({name: 'name1'} === {name: 'name1'}); // false

It prints false because the compared objects haven't the same references even if they are similar.它打印false ,因为即使比较的对象相似,它们也没有相同的引用。

So in your example the indexOf method returns -1 because the objects have not the same reference (again even if they looks like they are equal).因此,在您的示例中, indexOf方法返回 -1 因为对象的引用不同(即使它们看起来相等)。

Since you can't directly use indexOf you have to first get the object's reference with find and then you can use indexOf , like this:由于您不能直接使用indexOf ,因此您必须先使用find获取对象的引用,然后才能使用indexOf ,如下所示:

 const nodesData=[ {name:'name1'}, {name:'name2'}, {name:'name1'}, {name:'name3'}, ] const uniqData=[ {name:'name1'}, {name:'name2'}, {name:'name3'}, ] for (let i = 0; i < nodesData.length; i += 2) { const currentSource = nodesData[i]; const currentTarget = nodesData[i + 1]; const currentData = { source: uniqData.indexOf(uniqData.find(({name}) => name === currentSource.name)), target: uniqData.indexOf(uniqData.find(({name}) => name === currentTarget.name)), }; console.log(currentData); }

Note:笔记:

I used destructuring in order to directly get the name property我使用解构来直接获取name属性

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

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