gpt4 book ai didi

javascript - 编辑切片副本后原始数组仍然发生变化

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

我正在尝试保存 Geometry 对象顶点的原始坐标的副本。我尝试按照在 stackoverflow 上找到很多答案的方式复制该对象。

// create a Geometry object from a BufferGeometry
cityGeometry = new THREE.Geometry().fromBufferGeometry( child.geometry );

// properly copy the cityGeometry.vertices array
var originalPositions = cityGeometry.vertices.slice(0);

// change an element of the copy
originalPositions[0].z = 1000;
console.log(originalPositions[0]);
console.log(cityGeometry.vertices[0]);

// now change the original object
cityGeometry.vertices[0].z = 123;
console.log(originalPositions[0]);
console.log(cityGeometry.vertices[0]);

但是,如果我这样做,两个对象总是同时改变。控制台输出如下:

Vector3 {x: 0.8206260204315186, y: -0.4336470067501068, z: 1000}
Vector3 {x: 0.8206260204315186, y: -0.4336470067501068, z: 1000}
Vector3 {x: 0.8206260204315186, y: -0.4336470067501068, z: 123}
Vector3 {x: 0.8206260204315186, y: -0.4336470067501068, z: 123}

我在这里遗漏了什么吗?谢谢!

最佳答案

你可以使用:

originalPositions = JSON.parse(JSON.stringify( cityGeometry.vertices ));

as array.slice() 只进行浅拷贝。

关于javascript - 编辑切片副本后原始数组仍然发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43151718/

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