简体   繁体   中英

Changing one variable changes all others defined the same way

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:

<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?

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

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM