0

I have a constructor:

function a(x, y){\n
    this.array[x][y];
     for(var i = 0; i<x; i++){
         for(var j = 0l j<y; j++){
             this.array[i][j]=0;
         }
     }
}

How would I declare this.array correctly? (this.array is supposed to be a multidimensional array.

3
  • not sure what this.array[x][y]; is supposed to do? can you elaborate Commented Mar 5, 2018 at 20:09
  • The first thing you need to remember about Javascript, there isn't really such a thing as a multidimensional array. But you can have arrays that contain arrays, once you work out what that means, implementing a type of multidimensional array of X dimensions is possible. Commented Mar 5, 2018 at 20:10
  • this.array = Array.from({length: x}, () => Array(y).fill(0)) Commented Mar 5, 2018 at 20:13

2 Answers 2

1

If you want to initialize that array, use this approach:

                         +---- Length for outter array
                         |
                         v
this.array = Array.from({length: x}, () => Array(y).fill(0));
                                                ^
                                                |
                                                +--- This will initialize the nested arrays

function a(x, y){
  this.array = Array.from({length: x}, () => Array(y).fill(0));
  console.log(JSON.stringify(this.array, null, 2))
}

a(2, 3);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

1 Comment

the other way around, Array.from({length: x}, () => Array(y).fill(0)). check what happens with your code if you change this.array[0][0]=1; all columns are changed, as they all reference the same sub-array
0

a multidimensional array is an array of arrays

just declare an array, then fill it with the x arrays inside, each with y elements.

To keep the same style as your provided code, you can do something like this

    function a(x, y){
         var myArray = [];
         for(var i = 0; i < x; i++){
             myArray[i] = [];
             for(var j = 0; j < y; j++){
                 myArray[i][j] = 0;
             }
         }
         return myArray;
    }

    var exampleArray = a(3,4);
    console.log(exampleArray);

I wrote it like your snippet of code for understanding. However, there are better ways ('clearer' and probably more efficient, and more 'javascriptish') to write arrays. For example, see Ele's answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.