简体   繁体   English

JS多维数组空间域

[英]JS multidimensional array spacefield

i wanna generate a 3x3 field. 我想生成一个3x3的字段。 I want to do this with JS, it shall be a web application. 我想用JS做到这一点,它将是一个Web应用程序。

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. space[i] = false会将数组替换为单个布尔值false ,而不是填充刚创建的数组中的所有条目。 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 . 另外,您的for()循环条件是错误的,因为您没有初始化space的最后一个元素。 It should have been i < space.length . 应该是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: 其他功能也同样有效,但是下面是使用ES6的简单外观,适用于任何正方形网格:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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