curious... how would you write this Ruby in JS?
Array.new(3, Array.new(3, 0))
which returns
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
i've tried a variety of things but they all seem messy. i suppose some things just can't be as clean as Ruby, but how would you approach this?
maybe i'll learn a JS trick or two ;)
EDIT It was revealed that this Ruby code does not actually create 3 arrays. It creates 1 array, that the others reference. This was not the intention. I am looking for a way to easily map a 2 dimensional array with X amount of elements, and Y amount of nested elements in JS.
Also... This is a contrived example. the intension is to be able to substitute 3 with any number. this was just an example using 3.
You can define it like so:
var arr = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
Essentially you're explicitly defining it. However, this array contains references to three different arrays (making a total of 4). To make it behave like ruby, you would need to create a function that mimics this behavior:
function arr(size, element) {
var ret = [];
for(var i = 0; i < size; i++) {
ret.push(element);
}
return ret;
}
Then you could do:
var myArray = arr(3, arr(3, 0)); //myArray contains [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
This is more true to the behavior you see in ruby since each element in the array is a reference to the same array (making a total of just two arrays). You can verify this by doing myArray[0][1] = 2;
and then inspecting myArray
. You should see the second element in each of the arrays in myArray
set to 2.
If you just want an empty array container, just to keep track of the length, or to assign values later on, you can do this, a bit hacky but should work:
var a = [[,,],[,,],[,,]]
a[1][1] = 'foo'
alert(a[1][1]) //foo
The following is valid Javascript syntax, assuming you want to create 4 arrays:
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
EDIT:
Actually your ruby code only creates TWO arrays. One array is [0,0,0]
and the other array contains three references to that array. If you change array[0][2]
you also change array[1][2]
. Are you sure this is what you want? The equivalent javascript code would be:
var b = [0, 0, 0];
var a = [b, b, b];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With