search
HomeWeb Front-endJS TutorialHow to use javascript arguments object

How to use javascript arguments object

Jul 20, 2021 am 11:54 AM
javascript

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
JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor