Home > Article > Web Front-end > Detailed explanation of arguments object in Javascript_Basic knowledge
In the previous article we discussed the default parameters in JavaScript. In this article, we will discuss the arguments parameter object of JavaScript.
For the function in the example below, how can we do different processing according to the different parameters passed in?
// 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 situation. The arguments object is an array-like object. If you want to know more about the arguments object, please click here. We use the arguments object to change the above example:
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-like object, let’s test it:
//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:
return sorted;
}
sortArgs();
We can convert an array-like object into an array object as follows:
// 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 forward it to more people who need it. If the article is inappropriate, please leave a message to correct it.