0

I want to initialize and populate a two-dimensional array, but my solution doesn't seem to work. It only returns a function, not a value.

class Board{
    constructor(width,height,cols,rows)
    {
        this.width=width;
        this.height=height;
        this.cols=cols;
        this.rows=rows;
        this.array= function(){
            let array=[];
            for(let i=0;i<this.cols;i++)
            {
                array[i]=[];
                for(let j=0;j<this.rows;j++){
                    array[i][j]=0;
                }
            }
            return array;
        }
    }

4 Answers 4

4

There's no need for the inner function, just populate the array and assign it to the property.

class Board {
  constructor(width, height, cols, rows) {
    this.width = width;
    this.height = height;
    this.cols = cols;
    this.rows = rows;
    let array = [];
    for (let i = 0; i < this.cols; i++) {
      array[i] = [];
      for (let j = 0; j < this.rows; j++) {
        array[i][j] = 0;
      }
    }
    this.array = array;
  }
}

const b = new Board(2, 3, 4, 5);
console.log(b.array);

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

Comments

0

Can be easier

class Board {
  constructor(width, height, cols, rows) {
    this.width = width;
    this.height = height;
    this.cols = cols;
    this.rows = rows;
    this.array = [];
    for (let i = 0; i < this.cols; i++) {
      this.array.push(new Array(this.rows).fill(0));
    }
  }

Comments

0

You can directly put values on property no need to function

class Board {
  constructor(width, height, cols, rows) {
    this.width = width;
    this.height = height;
    this.cols = cols;
    this.rows = rows;
    let array = new Array(this.cols).fill(0).map(val=> new Array(this.rows).fill(0))
    this.array = array;
  }
}

const b = new Board(2, 3, 4, 5);
console.log(b.array);

Comments

0
this.array= function(){
    let array=[];
    for(let i=0;i<this.cols;i++)
    {
        array[i]=[];
        for(let j=0;j<this.rows;j++){
            array[i][j]=0;
        }
    }
    return array;
}

This just creates a function named this.array.

If you want this.array to hold the return value, call the function there itself.

this.array= (function(){
    let array=[];
    for(let i=0;i<this.cols;i++)
    {
        array[i]=[];
        for(let j=0;j<this.rows;j++){
            array[i][j]=0;
        }
    }
    return array;
})();

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.