gpt4 book ai didi

javascript - Array.prototype.indexOf() 在 React.js 中的工作方式是否不同

转载 作者:行者123 更新时间:2023-12-02 23:15:49 26 4
gpt4 key购买 nike

我试图理解这段代码是如何工作的,我使用 Array.prototype.indexOf() 来获取状态数组的索引,以便可以更新它。我被告知要在indexOf()的参数中传递一个对象,但我认为没有两个对象是相等的,那么indexOf()如何返回正确的索引,我在这里错过了什么吗?这是我的代码

 handleIncrement(counter){//passing object here from child component

const counters = [...this.state.counters];//cloning
const index = counters.indexOf(counter)//geting index of param counter
console.log(counter === index)//how did index return true if this returns false???
counters[index] = {...counter};// spread object onto index pos

counters[index].value++;//increment value
this.setState({counters})//updates state just fine no errors
}

最佳答案

您误解了.indexOf()indexOf 返回在数组中可以找到给定元素的第一个索引,如果不存在则返回 -1。因此,index 将是 counterscounter 的索引。简而言之,您将一个对象(counter)与一个数字(index)进行比较。

也就是说,这还取决于您如何在数组中搜索对象。如果尝试查找与特定键/值结构匹配的对象,则 .indexOf 将因您提到的原因而不起作用。正如 Gabriele 所指出的,如果使用引用进行搜索,它就会起作用。

如果无法使用引用,您可以使用 .findIndex() 作为替代方案。 ,或 .map(),并根据其属性之一查找对象,例如 id

const counters = [{id: 1, value: 0}, {id: 2, value: 0}, {id: 3, value: 0}, {id: 4, value: 0}];

const findBySameness = {id: 3, value: 0};
const findByRef = counters[2];

const indexBySameness = counters.indexOf(findBySameness);
console.log('Index by sameness: ', indexBySameness); // Do not find the object index
const indexByRef = counters.indexOf(findByRef);
console.log('Index by reference: ', indexByRef); // Found the object index

// If a reference to the object is not available you can use the following methods

// With .findIndex
const index3 = counters.findIndex(item => item.id === findBySameness.id)
console.log('Index: ', index3); // Found the object index

// With .map
const index2 = counters.map(item => item.id).indexOf(findBySameness.id);
console.log('Index: ', index2); // Found the object index

关于javascript - Array.prototype.indexOf() 在 React.js 中的工作方式是否不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57177877/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com