I am just wondering why it is not possible to make forEach on array of undefined.
Code:
var arr = new Array(5); // [undefined x 5]
//ES5 forEach
arr.forEach(function(elem, index, array) {
console.log(index);
});
//underscore each
_.each(arr, function(elem, index, array) {
console.log(index);
});
Both examples do not execute function.
Now to make foreach, I have to make:
var arr = [0,0,0,0,0];
Then make forEach on it.
I am trying to make an array with specified size and loop through it, avoiding for
loop. I think that it is clearer using forEach than for loop.
With array with length 5 it is not a problem, but it would be ugly with bigger arrays.
Why there is a problem looping through array of undefined values ?
JavaScript Array forEach() The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements.
There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.
Arrays can be created using a constructor with a single number parameter. An array with its length property set to that number and the array elements are empty slots.
Description. The forEach() method is an iterative method. It calls a provided callbackFn function once for each element in an array in ascending-index order. Unlike map() , forEach() always returns undefined and is not chainable.
Array(5)
is essentialy equivalent to
var arr = [];
arr.length = 5;
In javascript changing array's length doesn't set any values for it's numeric properties nor does it define those properties in the array object. So numeric properties are undefined instead of having undefined value. You can check it by using:
Object.keys(arr)
When iterating javascript iterates through numeric properties of the array, so if these don't exist, there is nothing to iterate over.
You can check it by doing:
var arr = Array(5)
//prints nothing
arr.forEach(function(elem, index, array) {
console.log(index);
});
arr[3] = 'hey'
//prints only 'hey' even though arr.length === 5
arr.forEach(function(elem, index, array) {
console.log(index);
});
The following code:
var arr = [undefined, undefined];
creates and array of length ===2
and sets the both numeric properties 0 and 1 to undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With