我认为如果我保留原始引用而不是简单地获取索引
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
。它究竟如何运作?
答案 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));
然后我会得到我需要的指定索引。