Vandervals
Vandervals

Reputation: 6054

Javascript forEach to loop n times

I know forEach is not very performant but I'm trying to use it (just a learning exercise) to loop something a number (n) of times.

I'm trying this, but I can't get it to work:

var i = 0;
new Array(10).prototype.foreach.call( function(){ i++; } );

Is it possible to use it this way? What is wrong with my code? Thanks!

Upvotes: 1

Views: 4002

Answers (2)

Jared Whipple
Jared Whipple

Reputation: 1171

If you want to use forEach instead of a for loop you can create an empty array of n items.

let i = 0;
[...Array(10)].forEach(() => {
    i++
});

You can also get the index:

[...Array(10)].forEach((_, i) => {
  console.log('index: ', i);
});

for is faster than forEach, but forEach is often preferred as you won't get off by n errors, and the speed difference is negligible unless you are dealing with a massive number of iterations. If you are dealing with massive iterations you really shouldn't be doing it with JavaScript anyway.

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

Internally, you can think of forEach as being defined like this:

Array.prototype.forEach = function(cb) {
    for( var i=0, l=this.length; i<l; i++) {
        cb(this[i]);
    }
}

Note that this is just a basic example, it's not really right XD But it's good enough for the point I'm making. Namely, this.

Normally, this is the array you're working on. But with the .call() call you've made, this === function(){ i++; }. A function's length is the number of arguments it accepts, which in your case is zero, so the code never runs. Even if it did (eg. function(x){ i++; }) the code within the function would not run, because that would have to be the second argument to .call() (which becomes the first argument of .forEach())

Try this:

[].forEach.call(new Array(10), function() {i++;});

This gets the forEach method, calls it on an array of length 10, passing the function as the callback argument.

I was wrong in the above. new Array(10) doesn't work the way you'd want it to. You would need some hackery like Array.apply(null, Array(10)).map(function () {}) to get an array that forEach will work on. You're better off just using for.

Upvotes: 4

Related Questions