Understanding Multidimensional Array Initialization in Javascript

Asked 1 years ago, Updated 1 years ago, 24 views

I can't do this

varhistArray=newArray(256);
varhistData = [histArray,histArray,histArray];
for(i=0;i<3;i++){
    for(j=0;j<256;j++){
        histData[i][j] = 0;
    }
}

This one will be initialized properly, but why is this?

varhistData=[histArray,histArray,histArray];
for(j=0;j<3;j++){
    histData[j] = new Array(256);
    for(i=0;i<256;i++){
        histData[j][i] = 0;
    }
}

javascript

2022-09-30 19:43

3 Answers

varhistData=[histArray,histArray,histArray];

There is only one instance of histArray, so it's always

histData[0][n]==histData[1][n]==histData[2][n]==histArray[n]

That's what happens.For example, if histData[0][1] is substituted for histData[1][1] and histData[2] [1] and histArray[1] will be the same value (because they all point to the same instance).

Therefore, you need to initialize as follows:

varhistData=[newArray(256), newArray(256), newArray(256)];


2022-09-30 19:43

In the first code example, histData[0], histData[1], histData[2] all point to the same container.Therefore, it would be strange to try to use histData[n][m] initialized in the first code example.

In the second code example, new Array(256) on the third line provides a new container, so histData[0], histData[1], histData[2] all refer to different containers.So you will be able to use it the way you want.


2022-09-30 19:43

JavaScript 1.7 has a convenient array.

 function range (begin, end) {
  for(leti=begin;i<end;i++){
    yieldi;
  }
}

varhistData = [[0 for each(jin range(0,256))] for each(i in range(0,3));


2022-09-30 19:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.