-1

i am a javascript newbie. I have a 9*9 grid for my sudoku game. The html is such that each box of the grid is an inputelement with id like r1c4 where 1 is the row number and 4 is column number. I have half filled grid.I needed to store all the numbers in the grid in a two dimensional array.I have created the following function fo:

function getValues(){

    var grid = new Array();
    var colData = new Array();
    var targetId;

    for(var i=1;i<=9;i++)
    {
        for(var j=1;j<=9;j++)
        {   
            targetId = 'r' + i + 'c' + j;
            colData[j-1] = document.querySelector('#'+targetId).value;

        }
        grid[i-1] = colData;
        console.log(grid[i-1]); // here logged correctly
    }
    return grid; // here returned wrong
} 

The problem i am facing is that the returned array consists of only the last element repeated 9 times. I am logging the stored value every time by using console.log(grid[i-1]); and it is giving correct results.I am not getting it.

Regards.

1
  • Great answers on this page. Don't know who downvoted your question but I +1'd to balance it :) Commented Apr 9, 2014 at 15:21

4 Answers 4

2
grid[i-1] = colData;

You are not copying colData to grid[i-1], but simply making grid[i-1] a reference to colData. So, all the elements in your array are just references to the same object, colData.

To fix this problem, you need to create a new Array on every iteration. So, I would have done it like this

function getValues() {
    var grid = [], colData, targetId;

    for (var i = 1; i <= 9; i++) {
        colData = [];      // new Array on every iteration
        for (var j = 1; j <= 9; j++) {
            targetId = 'r' + i + 'c' + j;
            colData.push(document.querySelector('#' + targetId).value);
        }
        grid.push(colData);
    }
    return grid;
}
Sign up to request clarification or add additional context in comments.

Comments

2

You need to create a new colData per iteration rather than using the same one each time.

for(var i=1;i<=9;i++)
{
  var colData = new Array();
   ...

Comments

2

Try either moving colData = new Array() (or better, colData = [];) inside the i for loop.

OR use grid[i-1] = colData.slice(0);.

Either way, you need to create a new array for each row, not just re-use the old one.

Comments

2

You're using the same Array object for every single column, and just overwriting the values. You're pushing 9 references to that same array into your grid.

You need to move var colData = new Array(); inside the loop so you're making a new Array for each column.

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.