gpt4 book ai didi

javascript - Array.splice 重复编辑并在 之后插入,意外结果

转载 作者:行者123 更新时间:2023-11-30 10:58:20 24 4
gpt4 key购买 nike

在以下示例 ( https://jsfiddle.net/dhkzwxr1/2/ ) 中:我试着理解 splice 的行为

const arr = [];
arr[0] = {name:"Jani",age:24};
arr[1] = {name:"Hege",age:32};
arr[2] = {name:"Stale",age:52};
arr[3] = {name:"Kai Jim",age:42};
arr[4] = {name:"Borge",age:25};

arr.splice(1, 0, {name:"Lene",age:27});
console.log(arr);

插入位置

按预期表现

const arr2 = [];
arr2[0] = {name:"Jani",age:24};
arr2[1] = {name:"Hege",age:32};
arr2[2] = {name:"Stale",age:52};
arr2[3] = {name:"Kai Jim",age:42};
arr2[4] = {name:"Borge",age:25};

const jani = arr2[0];

jani.age = 19

arr2.splice(1, 0, jani);
console.log(arr2);

输出:

Array(6)
0: {name: "Jani", age: 19}
1: {name: "Jani", age: 19}
2: {name: "Hege", age: 32}
3: {name: "Stale", age: 52}
4: {name: "Kai Jim", age: 42}
5: {name: "Borge", age: 25}
length: 6

为什么 arr2[0].age === 19 而不是 24?

最佳答案

这不是 slice 的问题。发生的情况是,JavaScript 中的对象与所有其他非原始值一样,通过引用传递。

所以即使你将一个对象插入数组,然后更新它,变量也会有更新后的值。我认为最重要的是要理解 jani 变量在你的情况下没有对象的实际值,而只是对它的引用。

关于javascript - Array.splice 重复编辑并在 之后插入,意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59108647/

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