JavaScript arguments object application example

  • 2020-03-30 03:58:40
  • OfStack

The arguments object

In function code, special object arguments are used, so developers can access them without specifying the parameter names.

For example, in the function sayHi(), the first argument is message. You can also access this value with arguments[0], which is the value of the first argument (the first argument at position 0, the second argument at position 1, and so on).

Therefore, you can override the function without explicitly naming the parameters:


function sayHi() {
if (arguments[0] == "bye") {
return;
}

alert(arguments[0]);
}

Number of detection parameters

You can also use the arguments object to check the number of arguments to a function, just by referring to the property arguments. Length.

The following code will output the number of parameters used each time the function is called:


function howManyArgs() {
alert(arguments.length);
}

howManyArgs("string", 45);
howManyArgs();
howManyArgs(12);

The code above displays "2", "0", and "1" in turn.

Note: unlike other programming languages, ECMAScript does not verify that the number of arguments passed to a function is equal to the number of arguments defined by the function. Functions defined by the developer can take any number of arguments (up to 255, according to Netscape documentation) without causing any errors. Any missing arguments are passed to the function as undefined, and any extra arguments are ignored.
Analog function overload

Use the arguments object to determine the number of arguments passed to the function to simulate function overload:


function doAdd() {
if(arguments.length == 1) {
alert(arguments[0] + 5);
} else if(arguments.length == 2) {
alert(arguments[0] + arguments[1]);
}
}

DoAdd (10); / / output "15"
DoAdd (40, 20); / / output "60"

When there is only one argument, the doAdd() function adds 5 to the argument. If you have two arguments, you add them together and return their sum. So doAdd(10) outputs "15", while doAdd(40, 20) outputs "60".

Not as good as reloading, but enough to get around the limitations of ECMAScript.


Related articles: