How to create a multidimensional array with an object as default value in Javascript? -


i'm having trouble when want create multidimensional array.

i don't know why strange behavior when want create multidimensional array object default value.

i have used different ways like:

the trouble appears when want change of fields of object.

function matrix( rows, cols, defaultvalue){    var arr = [];    // creates lines:    for(var i=0; < rows; i++){        // creates empty line        arr.push([]);        // adds cols empty line:        arr[i].push( new array(cols));        for(var j=0; j < cols; j++){          // initializes:          arr[i][j] = defaultvalue;        }    }  	return arr;  }    var myarray = matrix(5, 5, {  	status: 'ok'  });      myarray[2][1].status = 'not ok';    console.log('strange behavior', myarray);

the change expands on other positions.

can me?

because store reference 1 , same object on , on again, have behaviour described. separate objects, use object.assign, make (shallow) copy of defaultvalue each time need it:

arr[i][j] = object.assign({}, defaultvalue); 

with other es6 features, code this:

function matrix( rows, cols, defaultvalue){    return array.from(array(rows),        row => array.from(array(cols), cell => object.assign({}, defaultvalue))    );  }  var myarray = matrix(5, 5, {  	status: 'ok'  });    myarray[2][1].status = 'not ok';    console.log('correct behavior', myarray);
.as-console-wrapper { max-height: 100% !important; top: 0; }


Comments

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -