How to fill the array in another way?

0

window.addEventListener("load", function(){
  
  // Para uso
  var matriz = [];
  var i = 0;
  
  for (i; i<=50; ++i) {
    
    matriz.push(i);
    
  }
  
  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>

I do a for to fill the array with 50 numbers and so then show by screen all the array with forEach , but how could I fill the array without loops? (but if you use the forEach to show the numbers)

    
asked by Eduardo Sebastian 12.06.2017 в 22:02
source

2 answers

5

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
    
answered by 12.06.2017 / 22:08
source
3

You could do the following to create an array of 50 elements with consecutive numbers

window.addEventListener("load", function() {

  var matriz = Array(50).fill().map(Number.call, Number);

  matriz.forEach(function(e) {
    document.write(e + '\n');
  });

});
    
answered by 12.06.2017 в 22:09