简体   繁体   中英

Edit specific element in JavaScript 2D array and not the column

When manually creating a 2D array and editing a specific element I get the desired results. If I create it with a for loop and edit one element in the array, it changes the whole array in each row, in turn editing the whole column.

Is there a better way to create 2D arrays with a for loop to avoid this behavior?

var grid = [1,2,3];
var gridRows = ["O","O","O"];

for (var i = 0; i < grid.length; i++) {
    for(var j = 0; j < grid.length; j++) {
        grid[i] = gridRows;
    }
}

Image of the for loops output

//--------------------
//The manually created 2D Array
manualGrid = [["O","O","O"],["O","O","O"],["O","O","O"]];

Image of the manual methods output in console

Arrays are objects in javascript which are passed by reference . To avoid this just change your code to :

var grid = [1,2,3];
var gridRows = ["O","O","O"];

for (var i = 0; i < grid.length; i++) {
    for(var j = 0; j < grid.length; j++) {
        grid[i] = JSON.parse(JSON.stringify(gridRows));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM