3

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?

xdazz
  • 158,678
  • 38
  • 247
  • 274
3y3
  • 802
  • 1
  • 6
  • 18

5 Answers5

4

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.

raina77ow
  • 103,633
  • 15
  • 192
  • 229
2

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]
Roby Cigar
  • 766
  • 2
  • 14
  • 28
0

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

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • Haha =) I know about common for/white, but I prefer to work with forEach - it provide best encapsulation of code (speed is not important) – 3y3 Apr 29 '14 at 09:11
  • @3y3 What exactly you are trying to do? What should be the output? – thefourtheye Apr 29 '14 at 09:12
  • @3y3 Does the updated answer, look fine to you? It is a neat hack ;-) – thefourtheye Apr 29 '14 at 09:20
  • based on answer of @raina77ow I can propose ```console.log(Array.apply(null, new Array(30)).map(Number.call, Number));```. Length trick is also interesting. Thanks. – 3y3 Apr 29 '14 at 09:42
  • @3y3 Read the linked question to have a deeper understanding of how that works. I must say, its really worth reading :-) – thefourtheye Apr 29 '14 at 09:44
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([]);
        */
    }
Luketep
  • 181
  • 1
  • 9
-2

If you insist foreach

var data = [1, 2, 3];
data.forEach(function(x) {
    console.log(x);
});
jhyap
  • 3,779
  • 6
  • 27
  • 47