简体   繁体   中英

JS multidimensional array spacefield

i wanna generate a 3x3 field. I want to do this with JS, it shall be a web application.

All fields shall inital with false. But it seems so that my code is not working correctly, but i don't find my fault. The goal is, that every spacesector is accessible.

Thats my idea:

// define size
var esize = generateSpace(3);



}

space[i] = false is replacing the array with a single boolean value false , not filling in all the entries in array you just created. You need another loop to initialize all the elements of the array.

function generateSpace(x) {
    var space = [];
    for (var i = 0; i < x; i++) {
        space[i] = [];
        for (var j = 0; j < x; j++) {
            space[i][j] = false;
        }
    }
    return space;
}

Also, your for() loop condition was wrong, as you weren't initializing the last element of space . It should have been i < space.length .

And when it's done, it needs to return the array that it created.

Since I got somewhat bored and felt like messing around, you can also initialize your dataset as shown below:

function generateSpace(x) {
    return Array.apply(null, Array(x)).map(function() {
        return Array.apply(null, Array(x)).map(function() {
            return false;
        });
    });
}

The other functions work equally well, but here's a fairly simply looking one using ES6 that works for any square grid:

function generateSpace(x) {
    return Array(x).fill(Array(x).fill(false));
}

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