无法获取数组

时间:2018-01-08 01:38:29

标签: javascript ecmascript-6

我认为如果我保留原始引用而不是简单地获取索引

const selected = {id: "abcd123", quantity: "5"};
const location = [
  {id: "abcd123", quantity: "3"},
  {id: "abcd1234", quantity: "3"},
];
const filterLocation = location.filter(loc => loc.id === selected.id);
console.log(location.indexOf(filterLocation));

我希望它会记录0,但它总是返回-1。它究竟如何运作?

3 个答案:

答案 0 :(得分:1)

  const selected = {id: "abcd123", quantity: "5"};
  const location = [
    {id: "abcd123", quantity: "3"},
    {id: "abcd1234", quantity: "3"},
  ];
 const filterLocation = location.filter(loc => loc.id === selected.id);

 console.log(location.findIndex(value => value.id === filterLocation[0].id )));

filter返回一个新数组。因此,您只需要在此示例中访问该值filtered

更改indexOf的{​​{1}}。 findIndex是一个对象数组,因此您需要再次迭代所有数组以恢复索引。当然,它仅适用于此示例,您也可以在同一location操作中恢复索引。

filter

答案 1 :(得分:1)

首先,methods不包含与filterLocation相同的任何对象。它包含唯一具有相同location字段的对象,但id字段不同。其次,quantity方法对非标量参数不起作用。

答案 2 :(得分:0)

抱歉我的错误

我想我应该切换到findIndex而不是indexOf

const selected = {id: "abcd123", quantity: "5"};
const location = [
 {id: "abcd123", quantity: "3"},
 {id: "abcd1234", quantity: "3"},
];
const filterLocation = location.filter(loc => loc.id === selected.id);
console.log(location.findIndex(loc => loc.id === selected.id));

然后我会得到我需要的指定索引。