Filling up a 2D array with random numbers in javascript

前端 未结 3 1403
轮回少年
轮回少年 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 08:58

    Try removing the comma from...

    ground[[i],[j]] = (Math.random() * 5 | 0) + 6;
    

    ...in your 'clean' version. Also, your incrementing 'i' in both for loops:

    for (var i = 0 ; i < 15; i++) {
    for (var j = 0; j < 9; i++) {
    

    Hopefully these changes make it work for you :)

    0 讨论(0)
  • 2021-01-13 09:02

    Here's a quick example. I've created a function that will take in a width and height parameter and generate the size requested. Also I placed your tile function inside generate ground to keep it private, preventing other script from invoking it.

    var ground = generateGround(10, 10); //Simple usage
    
    function generateGround(height, width)
    {
      var ground = [];
      for (var y = 0 ; y < height; y++) 
      {
        ground[y] = [];
        for (var x = 0; x < width; x++) 
        {
            ground[y][x] = tile();
        }  
      }
      return ground;
    
      function tile()
      {
        return (Math.random() * 5 | 0) + 6;
      }
    }
    

    http://jsbin.com/sukoyute/1/edit

    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题