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.
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!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

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.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
