Filling up a 2D array with random numbers in javascript

前端 未结 3 1402
轮回少年
轮回少年 2021-01-13 08:24

I\'m really sorry if anything like this has been posted here before but I couldn\'t find anything, I\'m kinda new to the site still!

So for a while now I\'ve been

3条回答
  •  执念已碎
    2021-01-13 09:05

    You were thinking in the right direction but there are some errors in your code ;)

    • You have to initialize the array first before you can push elements into it.
    • And you were counting i++ twice

    Javascript

    var ground = []; // Initialize array
    for (var i = 0 ; i < 15; i++) {
        ground[i] = []; // Initialize inner array
        for (var j = 0; j < 9; j++) { // i++ needs to be j++
            ground[i][j] = (Math.random() * 5 | 0) + 6;
        }
    }
    

    Maybe even better (reusable)

    function createGround(width, height){
        var result = [];
        for (var i = 0 ; i < width; i++) {
            result[i] = [];
            for (var j = 0; j < height; j++) {
                result[i][j] = (Math.random() * 5 | 0) + 6;
            }
        }
        return result;
    }
    // Create a new ground with width = 15 & height = 9
    var ground = createGround(15, 9);
    

提交回复
热议问题