gpt4 book ai didi

javascript - ReactJS 中的 "IndexOf"函数不像 vanilla JS 方法那样工作

转载 作者:行者123 更新时间:2023-11-30 08:20:39 25 4
gpt4 key购买 nike

我有一个计数器应用程序,它只是增加其组件状态。

这是沙盒应用链接:https://codesandbox.io/s/5mxqzn001k .您可以在文件 src/components/counters.jsxline 30 中看到 counters.indexOf(counter) 找到目标对象并设置它的新值(value)并且有效。

handleIncrement = counter => {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counter };
counters[index].value++;
this.setState({ counters });
};

我试图在这个链接中复制在 vanilla js 方法中找到目标对象的函数: https://repl.it/@stoic25/TrickyForsakenLamp但我想知道为什么它不起作用?

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

let myArr = state.counters.indexOf({ id: 4, value: 0 });
console.log( myArr );
// returns -1

ReactJS 的“indexOf”函数行为是否与 vanilla js 不同?

最佳答案

只有当对象引用完全相同的对象实例时,对象才彼此相等。如果将数组中对象的引用传递给indexOf函数,它会通过比较引用找到索引,但如果传递新对象,它不会比较对象的每个键来找到的索引数组中的对象。对于你的第二个例子,试试看它会起作用:

const state = {
counters: [
{ id: 1, value: 4 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 }
]
};
let obj=state.counters[3]
let myArr = state.counters.indexOf(obj);
console.log( myArr );

在您的第一个 React 示例中传递给 handleIncrement 函数的计数器对象是对您 state.counters 中对象的引用,因此它返回其索引。

关于javascript - ReactJS 中的 "IndexOf"函数不像 vanilla JS 方法那样工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54140609/

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