The arguments
object in JavaScript is an odd wart—it acts just like an array in most situations, but it's not actually an array object. Since it's really something else entirely, it doesn't have the useful functions from Array.prototype
like forEach
, sort
, filter
, and map
.
It's trivially easy to construct a new array from an arguments object with a simple for loop. For example, this function sorts its arguments:
function sortArgs() {
var args = [];
for (var i = 0; i < arguments.length; i++)
args[i] = arguments[i];
return args.sort();
}
However, this is a rather pitiful thing to have to do simply to get access to the extremely useful JavaScript array functions. Is there a built-in way to do it using the standard library?
sort
has permeated all the answers, but sorting was just one example of something you could do with a proper array. The intent was to get the array. I can't even blame the question because it properly says "for example". Yet every answer has decided to roll in "sort" into the example for converting the arguments to an array -- sometimes too tightly conflating sorting with getting an array of arguments. – Trawl