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?

1
  • 1
    looks like the last element in the array should have a value Commented Aug 23, 2011 at 18:58

1 Answer 1

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);
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

You could also just do map_store[i] = [];
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)
@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 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 :)
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 stackoverflow.com/questions/7375120/… 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."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.