'JS arguments.forEach is not a function
So this code works perfectly
var arr = [1, 2, 3, 4];
arr.forEach(function (el) {
console.log(el);
})
But if i try to do this:
function printArgsInfo() {
arguments.forEach(function (el) {
console.log(el);
});
}
printArgsInfo(2, 3, 2.5, -110.5564, false);
arguments.forEach is not a function
Even though arguments is an array and if Itry to do this with a for in loop it still works.
Solution 1:[1]
arguments is an array-like object, but not an array:
var doThing = function() {
console.log(arguments.constructor.name)
console.log([].constructor.name)
}
doThing("someArgument")
Will return Object for arguments and Array for the empty array [].
ES6 and newer
With ES6, you could use rest parameters ..., as torazaburo suggests.
The rest parameter syntax allows us to represent an indefinite number of arguments as an array.
function printArgsInfo(...args) {
args.forEach(el => console.log(el));
}
printArgsInfo(2, 3, 2.5, -110.5564, false);
ES5 and older
For ES5 and older, you could borrow the method from Array#forEach and call it with argument as thisArg.
function printArgsInfo() {
[].forEach.call(arguments, function (el) {
console.log(el);
});
}
printArgsInfo(2, 3, 2.5, -110.5564, false);
Solution 2:[2]
Per the MDN Docs:
The arguments object is an Array-like object corresponding to the arguments passed to a function.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
So, it is not a true array and does not share the Array object's prototype -- which is where the forEach method is defined.
Interestingly, also from the MDN docs:
You can also use the Array.from() method or the spread operator to convert arguments to a real Array
var args = Array.from(arguments);
So, here is a working example with your code:
function printArgsInfo() {
var args = Array.from(arguments);
args.forEach(function (el) {
console.log(el);
});
}
printArgsInfo(2, 3, 2.5, -110.5564, false);
Solution 3:[3]
Even though arguments is an array
It isn't.
function myFunc() {
console.log(arguments instanceof Array);
}
myFunc(1,2,3);
The Arguments object is an array-like object. It isn't an array.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mikemaccana |
| Solution 2 | |
| Solution 3 | mikemaccana |
