gpt4 book ai didi

Record a variable array as it is at a given moment, JavaScript [duplicate](按给定时刻的原样记录变量数组,JavaScript[复制])

转载 作者:bug小助手 更新时间:2023-10-26 20:56:09 26 4
gpt4 key购买 nike




In the following code, I want oneArray to remain what it is when it's declared, namely [1, 2, 3]. Instead, it changes when myArray changes. Is there a way to prevent this?

在下面的代码中,我希望OneArray在声明时保持原样,即[1,2,3]。相反,它会随着myArray的更改而更改。有没有办法防止这种情况发生?


let myArray = [1, 2, 3];
const oneArray = myArray;

console.log(myArray);
console.log(oneArray);

myArray.pop(); // When myArray changes, so does oneArray.

console.log(myArray);
console.log(oneArray);

I tried using const as opposed to let, but as you can see, it does not solve the problem. Being a beginner, I didn't know what else to try.

我尝试使用const而不是let,但如您所见,它不能解决问题。作为一个初学者,我不知道还能尝试什么。


更多回答

Specifically for array of numbers, you can copy them with array.slice(), without arguments

特别是对于数字数组,您可以使用array.slice()不带参数地复制它们

@ParzhfromUkraine - or, any array of any combination of primitives

@ParzhfromUkraine -或者,任何基元组合的数组

That first answer in the duplicate is good for your use-case (creating a shallow copy of the array). However, if you ever have an array of objects for example, structuredClone provides a way to deep-copy that data too.

副本中的第一个答案适用于您的用例(创建数组的浅表副本)。但是,如果您曾经有一个对象数组,例如,StructuredClone也提供了一种深度复制数据的方法。

优秀答案推荐

The reason that both your arrays are changing at the same time is because they are pointing to the same object. In order to have the arrays be totally seperate, you should use the spread operator. This will create a new object for oneArray to point to. Ex

这两个数组同时更改的原因是它们指向相同的对象。为了使数组完全分开,您应该使用扩散运算符。这将为OneArray创建一个要指向的新对象。例如


oneArray = [...myArray]

更多回答

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