gpt4 book ai didi

javascript - 即使使用切片,数组的副本也会更改原始数组

转载 作者:行者123 更新时间:2023-12-03 08:16:08 25 4
gpt4 key购买 nike

我正在尝试创建数组的副本,以便可以在保存原始数组的同时对副本进行更改。我正在使用切片函数来复制数组,但由于某种原因它仍在更改两个数组。嵌入的代码将无法运行,因为我使用的是无法导入的自定义字体

let font;
let num1;

function preload() {
font = loadFont("Pacifico-Regular.ttf")
}
function setup() {
createCanvas(350, 350);
num1 = new num("1", 350 / 2, 350 / 2, 200)
num1.randomize(-5, 5)
num1.show()
}
function draw() {}

class num {
constructor(text, centerX, centerY, fontSize) {
this.text = text;
this.centerX = centerX;
this.centerY = centerY;
this.fontSize = fontSize;
this.oldArray = font.textToPoints(this.text, this.centerX, this.centerY, this.fontSize);
this.newArray = this.oldArray.slice(); //Here is where I make a copy of the Array
}
//Randomizes old array
randomize(min, max) {
for (let i = 0; i < this.oldArray.length; i++) {
this.oldArray[i].x = this.oldArray[i].x + random(min, max);
this.oldArray[i].y = this.oldArray[i].y + random(min, max);
}
}
//Draws new array
show() {
beginShape()
for (let i = 0; i < this.newArray.length; i++) {
vertex(this.newArray[i].x, this.newArray[i].y)
}
endShape(CLOSE)
}
//Moves new array
move(x, y) {
for (let i = 0; i < this.newArray.length; i++) {
this.newArray[i].x = this.newArray[i].x + x;
this.newArray[i].y = this.newArray[i].y + y;
}
}
//Returns old array
return() {
this.newArray = this.oldArray.slice();
}
}
<script src="https://cdn.jsdelivr.net/npm/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="28581d6819061c0618" rel="noreferrer noopener nofollow">[email protected]</a>/lib/p5.js"></script>

最佳答案

您不是在更改数组,而是在改变数组中的对象。你不希望这样。

const myObj = {
x:1,
y:1
};

const myArray = [myObj];
const myNewArray = [...myArray];

myNewArray[0].x = 2;
console.log(myArray[0].x); // 2!!!!!

如果您要更改数组中的对象并且不希望它发生变化,请执行以下操作:

const myObj = {
x:1,
y:1
};

const myArray = [myObj];

// helper function that will perform a mutation at a given position
// and ignore all other positions
const mutateObjectAtPosition = (pos,mutation) => [...myArray].map((o,i) => i === pos ? mutation(o) : o)

// at position 0, return a **new object** with x set to 2
const myNewArray = mutateObjectAtPosition(0,(o) => ({...o,x:2}));

console.log(myNewArray !== myArray); // true, different references
console.log(myNewArray[0].x); // 2
console.log(myArray[0].x); // 1


关于javascript - 即使使用切片,数组的副本也会更改原始数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69319611/

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