Filling up a 2D array with random numbers in javascript

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

提交回复
热议问题