0

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

1 Answer 1

1

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));
    }
}
Sign up to request clarification or add additional context in comments.

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.