In the previous article, we discussed the default parameters in javascript. In this article, we will discuss the arguments parameter object of javascript.
How do we do different processing based on the passed parameters in a function in the following example?
The code copy is as follows:
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 an arguments object that can handle the above situations. The arguments object is an array object. If you want to know the details of the arguments object, please click here. We use the arguments object to change the above example:
The code copy is as follows:
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 have said above that the arguments object is an array object of class. Let's test it below:
The code copy is as follows:
function getName() {
console.log(Array.isArray(arguments));
}
//will output false
getName("benjamin");
The above test results can be seen:
It is not an array object, so what is the difference between it and an array object? Please click here for details.
Executing the following example will throw an error:
The code copy is as follows:
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 like the following:
The code copy is 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));
If you feel this article is helpful to you, I hope to pass it on to more people in need. If there is any inappropriate article, please leave a message to correct it.