Question

I need to iterate from 0 to 30, but I want to do this with help of forEach:

new Array(30).forEach(console.log.bind(console);

Of course this does not work, therefor I do:

new Array(30).join(',').split(',').forEach(console.log.bind(console));

Is there other ways to fill empty arrays?

Was it helpful?

Solution

Actually, there's a simple way to create a [0..N) (i.e., not including N) range:

var range0toN = Object.keys(Array.apply(0,Array(N)));

Apparently Object.keys part can be dropped if you only want to get a proper array of N elements.

Still, like others said, in this particular case it's probably better to use for loop instead.

OTHER TIPS

if you want all of item have same value, do this

var arrLength = 4
var arrVal = 0

var newArr = [...new Array(arrLength)].map(x => arrVal);
// result will be [0, 0, 0, 0]

You could try using a for loop. new Array is not a best practise

    var index,      // we use that in the for loop
        counter,    // number of elements in array
        myArray;    // the array you want to fill

    counter = 30;
    myArray = [];

    for (index = 0; index < counter; index += 1) {

        myArray[index] = [];
        /* 
        // alternative:
        myArray.push([]);
        // one-liner
        for (index = 0; index < counter; index += 1) myArray.push([]);
        */
    }

If you simply want to iterate, then use for loop like this

for (var i = 0; i < 30; i += 1) {
    ...
    ...
}

Actually, if you are looking for a way to create a range of numbers, then you can do

console.log(Array.apply(null, {length: 30}).map(Number.call, Number));

It will create numbers from 0 to 29. Source : Creating range in JavaScript - strange syntax

If you insist foreach

var data = [1, 2, 3];
data.forEach(function(x) {
    console.log(x);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top