Changing one variable changes all others defined in the same way.

I have JavaScript code that has 4 3-dimensional arrays, each of which has a size of 500x500x220 (all 220 values ​​in the last dimension are rarely used). Because of this large size, it is much faster to determine one such array, and then determine four arrays from this. The problem is that when I change the value in one array, it also changes in others. Here is 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>

Note that the function f()should only modify the array content, but also modify the array signs. Why is he doing this and how can I get around this?

In case that matters, I use HTA.

+4
1

.

:

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

ini. content[0], , signs[0] ini[0].

:

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

:

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

Source: https://habr.com/ru/post/1625632/


All Articles