更改一个变量会以相同的方式更改所有其他变量

时间:2020-12-02 02:05:45

I have a JavaScript code which has 4 3-dimensional arrays that are each of 500x500x220 dimension (all 220 values in the last dimension are rarely all used). Because of this large dimension, it's much faster to define one array like this and then define the four arrays from that one. The problem is that then, when I change a value in one array, it changes in the others also. Here's my code:

我有一个JavaScript代码,它有4个3维数组,每个数组都是500x500x220维度(最后一个维度中的所有220个值都很少使用)。由于这个大尺寸,定义一个这样的数组要快得多,然后从那个数组中定义四个数组。问题是,当我在一个数组中更改一个值时,它也会在其他数组中发生变化。这是我的代码:

<script type="text/javascript">
var content = new Array();
var signs = new Array();
var sens = new Array();
var props = new Array();
var ini = new Array();
for(i = 0; i < 500; i++){
        ini[i] = new Array();
        for(j = 0; j < 500; j++){
                    ini[i][j] = new Array();
        }
}
content = ini;
signs = ini;
sens = ini;
props = ini;
function f(){
        alert(signs[3][3][2]);            //Returns undefined
        content[3][3][2] = 2;
        alert(signs[3][3][2]);            //Returns 2
}
f();
</script>

Notice that the f() function is only supposed to change the content array but it also changes the signs array. Why does it do that and how do I get around it?

请注意,f()函数只应更改内容数组,但它也会更改符号数组。它为什么这样做,我该如何解决它?

In case it makes a difference, I'm using HTA.

如果它有所作为,我正在使用HTA。

1 个解决方案

#1


2  

With the help of this post about copying nested arrays.

在这篇关于复制嵌套数组的帖子的帮助下。

Your code:

你的代码:

content = ini;
signs = ini;
sens = ini;
props = ini;

makes the arrays to point to ini. That's why any reference to content[0], for instance, is a reference to signs[0] and ini[0] as well.

使数组指向ini。这就是为什么对内容[0]的任何引用,例如,也是对符号[0]和ini [0]的引用。

Use:

使用:

function copy(arr){
    var new_arr = arr.slice(0);
    for(var i = new_arr.length; i--;)
        if(new_arr[i] instanceof Array)
            new_arr[i] = copy(new_arr[i]);
    return new_arr;
}

to copy the arrays:

复制数组:

content = copy(ini);
signs = copy(ini);
sens = copy(ini);
props = copy(ini);

#1


2  

With the help of this post about copying nested arrays.

在这篇关于复制嵌套数组的帖子的帮助下。

Your code:

你的代码:

content = ini;
signs = ini;
sens = ini;
props = ini;

makes the arrays to point to ini. That's why any reference to content[0], for instance, is a reference to signs[0] and ini[0] as well.

使数组指向ini。这就是为什么对内容[0]的任何引用,例如,也是对符号[0]和ini [0]的引用。

Use:

使用:

function copy(arr){
    var new_arr = arr.slice(0);
    for(var i = new_arr.length; i--;)
        if(new_arr[i] instanceof Array)
            new_arr[i] = copy(new_arr[i]);
    return new_arr;
}

to copy the arrays:

复制数组:

content = copy(ini);
signs = copy(ini);
sens = copy(ini);
props = copy(ini);