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?

1
  • 1
    Use for loop instead. Commented Apr 29, 2014 at 9:05

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

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([]);
        */
    }

Comments

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

5 Comments

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 What exactly you are trying to do? What should be the output?
@3y3 Does the updated answer, look fine to you? It is a neat hack ;-)
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 Read the linked question to have a deeper understanding of how that works. I must say, its really worth reading :-)
-3

If you insist foreach

var data = [1, 2, 3];
data.forEach(function(x) {
    console.log(x);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.