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:
- https://stackoverflow.com/a/41435124/1741027
- https://stackoverflow.com/a/28625612/1741027
- https://stackoverflow.com/a/18116922/1741027
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
Post a Comment