Javascript 如何将相同的数组值分配给两个不同的变量
我有:Javascript 如何将相同的数组值分配给两个不同的变量,javascript,Javascript,我有: path数组,它包含成对的x,y坐标 configdictionary只包含当前路径(当然,config实际上包含一些参数,所以请不要尝试删除它) initialPath,应始终包含初始path值,而不进行任何更改 我希望我的当前(配置)路径相对于其初始值更改其x值: // create config which should store some params var config = {}; // initial array var path = [[0,0], [10,10]
数组,它包含成对的path
坐标x,y
dictionary只包含当前路径(当然,config实际上包含一些参数,所以请不要尝试删除它)config
,应始终包含初始initialPath
值,而不进行任何更改path
x
值:
// create config which should store some params
var config = {};
// initial array
var path = [[0,0], [10,10], [20,20]];
// initialPath is an array that I want to stay constant
// because new position of the path will be calculated by initial path
// (not current that is in config) multiply on some koefficient
var initialPath = [...path]; // deep copy path
config.path = [...path] // deep copy path
console.log("initialPath before", initialPath );
for (var i = 0; i < config.path.length; i++) {
for (var j = 0; j < config.path[i].length; j++) {
// I want initial path do NOT change here, but it does
config.path[i][0] = initialPath[i][0] * 2;
}
}
console.log("initialPath after", initialPath );
正如我们看到的,initialPath
改变了它的值
我想要的输出:
// initialPath before:
// Array(3)
// 0: (2) [0, 0]
// 1: (2) [10, 10]
// 2: (2) [20, 20]
// initialPath after:
// Array(3)
// 0: (2) [0, 0]
// 1: (2) [10, 10]
// 2: (2) [20, 20]
PS对于该问题,标题可能会混淆,因此如果您确切知道该问题的名称,请更改标题您正在制作数组的深度副本。这仍然是一个肤浅的副本。以下是制作深度拷贝的方法:
函数deepCopy(数组){
返回array.map(元素=>{
if(数组.isArray(元素))
返回副本(元素);
返回元素;
});
}
变量a=[1,2,3,4,5,6];
var b=深度复制(a);
console.log('before');
console.log('a',a);
console.log('b',b);
b[2][0]=7;
b[3][1]=8;
console.log('after');
console.log('a',a);
console.log('b',b)代码>您可以执行(对于这种情况)
const path=[[0,0]、[10,10]、[20,20];
const copyvaluesPath=path.map(x=>[…x]);//实深度复制路径
copyvaluesPath[0][0]=15
log(JSON.stringify(path))
console.log(JSON.stringify(copyvaluesPath))
.as控制台包装{max height:100%!important;top:0;}
两个新数组都直接指向路径(通过引用)
因此,您的config.path不仅改变了initialPath,还改变了path,然后将其传播到initialPath
我通过如下编辑数组声明删除了引用
var initialPath=Array([…path]);config.path=数组([…路径])
代码正确运行,其余的都一样
干杯 这回答了你的问题吗<代码>[…路径]
生成浅拷贝,而不是深拷贝。
// initialPath before:
// Array(3)
// 0: (2) [0, 0]
// 1: (2) [10, 10]
// 2: (2) [20, 20]
// initialPath after:
// Array(3)
// 0: (2) [0, 0]
// 1: (2) [10, 10]
// 2: (2) [20, 20]