Home >Web Front-end >JS Tutorial >How to use javascript arguments object

How to use javascript arguments object

青灯夜游
青灯夜游Original
2021-07-20 11:54:175149browse

Usage of javascript arguments object: 1. Get the number of actual parameters and formal parameters; 2. Modify the actual parameter values; 3. Change the number of actual parameters; 4. Check whether the parameters passed by the user meet the requirements. ; 5. When the number of parameters of the function is uncertain, it is used to access the actual parameter value of the calling function; 6. Traverse or access the value of the actual parameter.

How to use javascript arguments object

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

arguments object represents the actual parameter collection of the function, which can only be visible within the function body and can be accessed directly.

The length attribute and callee attribute of the arguments object are the most commonly used:

  • Use the length attribute to get the number of actual parameters of the function. The arguments object is only visible inside the function body, so arguments.length can only be used inside the function body.

  • Use the callee attribute to refer to the function where the current arguments object is located. Use the callee attribute to call the function itself within the function body. In anonymous functions, the callee attribute is useful. For example, it can be used to design recursive calls.

Example 1: Get the number of actual parameters and formal parameters

Use the arguments.length property to get the number of actual parameters of the function. The number of formal parameters of the function can be obtained using the length property of the function object. This property is a read-only property and can be used both inside and outside the function body.

The following example designs a checkArg() function to detect whether the formal parameters and actual parameters of a function are consistent. If they are inconsistent, an exception will be thrown.

function checkArg(a) {  //检测函数实参与形参是否一致
    if (a.length != a.callee.length)  //如果实参与形参个数不同,则抛出错误
    throw new Error("实参和形参不一致");
}
function f(a, b) {  //求两个数的平均值
    checkArg(arguments);   //根据arguments来检测函数实参和形参是否一致
    return ((a * 1 ? a : 0) + (b * 1 ? b : 0)) / 2;  //返回平均值
}
console.log(f(6));  //抛出异常。调用函数f,传入一个参数

Example 2: Modify the value of the actual parameter inside the function

In the following example, use a for loop to traverse the arguments object, and then pass the value of the loop variable into arguments , in order to change the actual parameter value.

function f() {
    for (var i = 0; i < arguments.length; i++) {  //遍历arguments对象
        arguments[i] = i;  //修改每个实参的值
        console.log(arguments[i]);  //提示修改的实参值
    }
}
f(3, 3, 6);  //返回提示0、1、2,而不是3、3、6

Example 3: Changing the number of actual parameters of the function

By modifying the length attribute value, you can also change the number of actual parameters of the function. When the length attribute value increases, the added actual parameter value is undefined; if the length attribute value decreases, the actual parameter value after the length length value will be discarded.

function f() {
    arguments.length = 2;  //修改arguments属性对象的length属性值
    for (var i = 0; i < arguments.length; i ++) {
        console.log(arguments[i]);
    }
}
f(3, 3, 6);  //返回提示3、3

Example 4: Check whether the parameters passed by the user meet the requirements

In the following example, use arguments.callee to obtain the anonymous function, and then obtain it through the length attribute of the function The number of formal parameters of the function, and finally comparing the number of actual parameters with the number of formal parameters to detect whether the parameters passed by the user meet the requirements.

function f(x,y,z) {
    var a = arguments.length();  //获取函数实参的个数
    var b = arguments.callee.length;  //获取函数形参的个数
    if (a != b_ {  //如果实参和形参个数不相等,则提示错误信息
        throw new Error("传递的参数不匹配");
    }else {  //如果实参和形参个数相同,则返回它们的和
        return x + y + z; 
    }
}
console.log(f(3,4,5));  //返回值12

arguments.callee is equivalent to the function name. In the above example, arguments.callee is equal to f.

Application of arguments object

In actual development, arguments object is very useful. Flexible use of the arguments object can improve the flexibility of using functions and enhance the adaptability and error correction capabilities of functions in abstract programming. The following combines several typical examples to demonstrate the application of arguments.

1) Using the arguments object can enhance the flexibility of function application. For example, if the number of parameters of the function is uncertain, or the number of parameters of the function is large, and you do not want to define each formal parameter one by one, you can omit defining parameters and directly use the arguments object in the function body to access the actual parameter values ​​of the calling function. .

Example 1

The following example defines an averaging function, which uses the arguments object to calculate the average of the parameters. When calling a function, you can pass in any number of parameters.

function avg() {  //求平均值
    var num = 0, 1 = 0;  //声明并初始化临时变量
    for (var i = 0; i < arguments.length; i ++) {  //遍历所有实参
        if (typeof arguments[i] != "number")  //如果参数不是数值
            continue;  //则忽略该参数值
        num += arguments[i];  //计算参数的数值之和
            1 ++;  //计算参与和运算的参数个数
    }    
    num /= 1;  //求平均值
    return num;  //返回平均值
}
console.log(avg(1,2,3,4));  //返回2.5
console.log(avg(1,2,"3",4));  //返回2.3333333333333335

Example 2

In page design, it is often necessary to verify form input values. The following example checks whether the value entered in the text box is a legal email address.

function isEmail() {
    if (arguments.length > 1) throw new Error("只能够传递一个参数");  //检测参数个数
    var regexp = /^\w+((-\w+) | (\.\w+)) *\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)8\.[A-Za-z0-9]+$/;  //定义正则表达式
    if (arguments[0].search(regexp) != -1)  //匹配实参的值
        return true;  //如果匹配则返回true
    else 
        return false;  //如果不匹配则返回false
}
var email = "1798017447@qq.com";  //声明并初始化邮箱地址字符串
console.log(isEmail(email));  //返回true

2) arguments object is a pseudo-class array, not an array. The values ​​of actual parameters can be traversed or accessed through the length attribute and bracket syntax. However, by dynamically calling methods, you can also use array methods, such as push, pop, slice, etc.

Example 3

Use arguments to simulate overloading. Implementation method: Use the arguments.length attribute value to determine the number and type of actual parameters and decide to execute different codes.

function sayHello() {
    switch(arguments.length) {
        case 0 :
            return "Hello";
        case 1 :
            return "Hello, " + arguments[0];
        case 2 :
            return (arguments[1] == "cn" ? "你好, " : "Hello, ") + arguments[0];
    };
}
console.log(sayHello());  //"Hello"
console.log(sayHello("Alex"));  //"Hello,Alex"
console.log(sayHello("Alex", "vn"));  //"你好,Alex"

Example 4

The following example uses the dynamic calling method to let the arguments object call the array method slice(), which can convert the function parameter object into an array.

function f() {
    return [].slice.apply(arguments);
}
console.log(f(1,2,3,4,5,6));  //返回[1,2,3,4,5,6]

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to use javascript arguments object. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn