If the numbers have to be consecutive you could do something like this:
window.addEventListener("load", function(){
// Para uso
var matriz = Array.apply(null, {length: 50}).map(Number.call, Number);
matriz.forEach(function(e) {
document.write(e + '\n');
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
</body>
</html>
The constructor of the Array object basically does (the code is simplified so that it is better understood):
function Array() {
var a = [];
for (var i = 0; i < arguments.length; i++) {
a.push(arguments[i]);
}
return a;
}
By passing to the apply an object with a length property equal to the desired length (50) instead of an array of arguments what we get is:
function Array() {
var a = [];
for (var i = 0; i < 50; i++) {
a.push(undefined);
}
return a;
}
What creates an Array of 50 positions with all its values initialized as undefined
.
The call to the map
method causes the callback function passed as an argument (in our case Number.call
) to be called once for each element of the array, passing it 3 arguments: the current value of the element, the index or position within the array and the array itself.
That is, for example, for the element in the 5th position of the array (index 4) the call will be:
Number.call(undefined, 4, [0,1,2,3,undefined,undefined,....]);
What would be equivalent to calling:
Number(4) // Que va a devolver 4