I want to make an array of random numbers between 0 and 1, so I tried:
var randList = _.map(new Array(5), Math.random);
But instead of getting the list of random elements that I expected, I got:
console.log(JSON.stringify(randList));
"[null,null,null,null,null]"
Why did I get an Array of null instead of random numbers?
Actually, you get an array of undefined
- and function passed into map
isn't fired even once. That happens because array created with new Array(Number)
constructor is a bit weird - even though its length is set up correctly, it doesn't actually have 0
, 1
etc. properties:
var arr = Array(5);
console.log(arr.length); // 5
console.log('0' in arr); // false
That's why, even though plain old for (var i = 0; i < arr.length; i++)
will work for iterating over this array, for (var i in arr)
won't work:
for (var i in arr) {
console.log(i); // won't be called even once!
}
And that's, I suppose, is more-o-less similar to what happens with Array.map (at which _.map is mapped):
var newarr = arr.map(function(el) {
console.log(el); // nope, still nothing
});
console.log(newarr); // [undefined x 5]
So what's the right way of creating such an array? Here it is:
var rightArr = Array.apply(0, Array(5)); // ah, the pure magic of apply!
// and here goes an array of randoms:
var randArr = rightArr.map(Math.random);
... but of course using _.times
is the way to go in this case. )
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