Some objects in JavaScript look like arrays, but aren’t. They are called array-like. This blog post looks at what exactly that means and how to best work with those objects.
arguments.lengthAnd you can access a single argument, e.g. read the first argument:
arguments[0]Array methods, however, have to be borrowed. You can do that, because most of those methods are generic.
arr.m(arg0, arg1, ...)All functions have a method call that allows you to perform the above invocation differently:
Array.prototype.m.call(arr, arg0, arg1, ...)The first argument of call is the value for this that m receives (in this case, arr). Because we access m directly and not via arr, we can now hand any this to that method. For example, arguments:
Array.prototype.m.call(arguments, arg0, arg1, ...)
function printArgs() {
Array.prototype.forEach.call(arguments,
function (arg, i) {
console.log(i+'. '+arg);
});
}
We have used method forEach generically. printArgs in use:
> printArgs()
> printArgs('a')
0. a
> printArgs('a', 'b')
0. a
1. b
You can even apply generic methods to ordinary objects:
> var obj = {};
> Array.prototype.push.call(obj, 'a');
1
> obj
{ '0': 'a', length: 1 }
In the above case, property length did not exist and was automatically created, with the initial value zero.
Array.prototype.slice.call(arguments)Compare: to create a copy of an array arr, you make the method call
arr.slice()