Arguments object in Javascript
- 2020-03-30 04:11:25
- OfStack
In the last article, we discussed default parameters in javascript. In this article, we'll discuss javascript arguments parameter objects.
For a function like this, how do we do different things depending on the parameters we pass in?
function addAll () {
// What do we do here?
}
// Should return 6
addAll(1, 2, 3);
// Should return 10
addAll(1, 2, 3, 4);
Fortunately, javascript has a arguments object that handles the above situation. The arguments object is a class array object. For more information about the arguments object, please click here. We use the arguments object to change the above example:
function addAll () {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
// Returns 6
addAll(1, 2, 3);
// Returns 10
addAll(1, 2, 3, 4);
We said above that the arguments object is an array of class objects, let's test it:
function getName() {
console.log(Array.isArray(arguments));
}
//will output false
getName("benjamin");
The above test results can be seen:
It's not an array object, so how is it different from an array object? Please click here for details.
Executing the following example throws an error:
function sortArgs () {
// Uncaught TypeError: undefined is not a function
sorted = arguments.sort()
return sorted;
}
sortArgs();
We can convert an array object into an array object as follows:
function sortArgs () {
// Convert arguments object into a real array
var args = [].slice.call(arguments);
// Now this will work!
sorted = args.sort()
return sorted;
}
//will output [1, 2, 3]
console.log(sortArgs(1,3,2));