0

I am try to set value get from String into 2D-Array.

But it does not work. error description in the picture.

My code:

data = "012021111"
function isGameOver(data){
var map = [[],[]];
var index = 0;
    for (var i = 0; i < 3; i++) {
        for (var j = 0; j < 3; j++) {
            map[i][j] = data[index];
            console.log("index: " +index+ ",i: " + i + ",j: " + j + ", data: " + map[i][j]);
            index++;             
        }            
    }        
 }

enter image description here

1 Answer 1

2

error in your code is because you initialize map = [[], []] that is map is an array containing two elements only which are again arrays. But you are trying to access map[2] which is undefined. A better solution would be to initialize map as an empty array and inside first for loop push arrays to map as required.

data = "012021111"
function isGameOver(data){
var map = [];
var index = 0;
for (var i = 0; i < 3; i++) {
    map.push([]);
    for (var j = 0; j < 3; j++) {
        map[i][j] = data[index];
        console.log("index: " +index+ ",i: " + i + ",j: " + j + ", data: " + map[i][j]);
        index++;             
    }            
}        
 }

isGameOver(data);

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.