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.
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 []
.
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);
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);
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);
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.
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