Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I create a random array using _.map(new Array(n), Math.random)?

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?

like image 614
cabbagebot Avatar asked Mar 21 '23 01:03

cabbagebot


1 Answers

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

like image 71
raina77ow Avatar answered Apr 25 '23 14:04

raina77ow