1

I have the following code, which attempts to generate a 2 dimensional array of random numbers:

var block_size = 32;
var can_width = can.width;
var color_depth = 12;
var passes = can_width / block_size;
var map_store = new Array(passes);

for(i=0;i<passes;i++) {
  for(j=0;j<passes;j++) {
    map_store[i] = new Array(passes);
    color = Math.random() * color_depth;
    map_store[i][j] = Math.round(color);
  }
}

which seems to work fine if i put console.log statements within the loop, however if I try to access the map_store array outside of the loops. all of it's elements are undefined. why is this?

GSto
  • 41,512
  • 37
  • 133
  • 184

1 Answers1

9

map_store[i] = new Array(passes); should be above the 2nd for loop. You're clearing your previous j values.

for(i=0;i<passes;i++) {
  map_store[i] = new Array(passes); // <--
  for(j=0;j<passes;j++) {
    color = Math.random() * color_depth;
    map_store[i][j] = Math.round(color);
  }
}
Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • 1
    You could also just do `map_store[i] = [];` – gen_Eric Aug 23 '11 at 18:59
  • There is no real benefit in this case as you know the length of the Array before hand. Why is `[]` generally better than `new Array`? (I know it is, but I don't know why) – Halcyon Aug 23 '11 at 19:01
  • 2
    @Frits van Campen Style really -- since the language *has* a built-in feature, might as well take advantage of it (even though `new Array(len)` and `[]` are slightly different when `len` is not 0). It should also be noted that [Array constructor](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array) is somewhat special in how it treats arguments. That is, `[x]` and `new Array(x)` are different while `[x,y]` and `new Array(x,y)` are the same. Awesome design :) –  Aug 23 '11 at 19:06
  • 1
    What Frits van Campen has is fine if you care for speed. Declaring new Array(500) and then overwriting each element is generally faster than var foo = []; and 500 pushes barring VM-specific optimizations. See my post on http://stackoverflow.com/questions/7375120/why-arr-is-faster-than-arr-new-array/7375418#7375418 for a detailed explanation from a performance perspective. You'll find in high-performance JS libs, new Array(x) is still used. Of course, we don't want pre-mature optimization either :); however, the point is that `[]` - like all best practices - is not a "law." – JSPP Sep 11 '11 at 04:48