Filling up a 2D array with random numbers in javascript

不想你离开。 提交于 2019-12-01 05:50:35

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);

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

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 :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!