Table of Contents
Implementation of JS variable parameters 1: arguments
Implementation of JS variable parameters 2: rest parameter (...)
Home Web Front-end JS Tutorial Detailed explanation of how JavaScript functions implement variable parameters? (Summary sharing)

Detailed explanation of how JavaScript functions implement variable parameters? (Summary sharing)

Aug 04, 2022 pm 02:35 PM
javascript function variable parameter

JS is a weakly typed language and cannot use the param keyword to declare that the formal parameter is a variable parameter like C#. So how to implement this variable parameter in js? The following article will talk about the implementation method of JavaScript function variable parameters. I hope it will be helpful to everyone!

Detailed explanation of how JavaScript functions implement variable parameters? (Summary sharing)

Implementation of JS variable parameters 1: arguments

What are arguments? How to implement variable parameters?

arguments is an array-like object corresponding to the arguments passed to the function.

In ES5, you can use the arguments object to implement variable parameters.

The length of the arguments object is determined by the number of actual parameters rather than the number of formal parameters. Formal parameters are variables that are re-opened in memory space within the function, but they do not overlap with the memory space of the arguments object. When both arguments and values ​​exist, the two values ​​are synchronized, but when one of them has no value, the value will not be synchronized for this valueless case.

<script>
function dynamicArgs() {
	var info = "今日签到的学生有:";
	for (let i = 0; i < arguments.length ; i ++) {
		if (i > 0) {
			info += ",";
		}
		info += arguments[i];
	}
	
	console.log(info);
}

dynamicArgs("张三", "李四");
dynamicArgs("张三", "李四", "王五", "马六");
dynamicArgs(["张三", "李四", "王五", "马六", "jack", "rose"]);
</script>
Copy after login
  • The parameters are not sure, so just don’t write them down.

  • You can write N multiple parameters when calling, or you can pass an array directly.

Execution effect:

Detailed explanation of how JavaScript functions implement variable parameters? (Summary sharing)

Summary:

1. It can be seen from the function definition , if variable parameters arguments are used in the function, there is no need to write formal parameters

2. When calling a function, multiple actual parameters

arguments objects can be passed directly to the function are local variables available in all (non-arrow) functions. You can use the arguments object to reference a function's arguments within a function. This object contains each argument passed to the function, with the first argument at index 0. For example, if a function is passed three arguments, you can reference them like this:

arguments[0]
arguments[1]
arguments[2]
Copy after login

Parameters can also be set:

arguments[0] = &#39;value&#39;;
Copy after login

arguments is an object, is not an Array. It is similar to Array, but does not have any Array properties except the length attribute and the index element. For example, it has no pop method. But it can be converted to a real Array:

So you can often see code like this:

// 由于arguments不是 Array,所以无法使用 Array 的方法,所以通过这种方法转换为数组
 
var args = [].slice.call(arguments);  // 方式一
var args = Array.prototype.slice.call(arguments); // 方式二
 
// 下面是 es6 提供的语法
let args = Array.from(arguments)   // 方式一
let args = [...arguments]; // 方式二
Copy after login

arguments# Properties on <span style="font-size: 16px;"></span>

    ##arguments.callee: Points to the currently executing function (in strict mode, ECMAScript version 5 (
  • ES5 ) Prohibited use of arguments.callee()<strong></strong>)
  • argunments.length: Points to the number of arguments passed to the current function
  • arguments. caller: Removed

arguments combined with remaining parameters, default parameters and destructed assignment parameters<span style="font-size: 16px;"></span>

1) in strict In mode, the existence of remaining parameters, default parameters and destructed assignment parameters will not change the behavior of the

arguments object, but it is different in non-strict mode

function func(a) { 
  arguments[0] = 99;   // 更新了arguments[0] 同样更新了a
  console.log(a);
}
func(10); // 99

// 并且

function func(a) { 
  a = 99;              // 更新了a 同样更新了arguments[0] 
  console.log(arguments[0]);
}
func(10); // 99
Copy after login

2) When it is not Functions in strict mode

do not contain remaining parameters, default parameters, and destructuring assignments, then the value in the arguments object will track the value of the parameter (and vice versa) . Look at the following code:

function func(a = 55) { 
  arguments[0] = 99; // updating arguments[0] does not also update a
  console.log(a);
}
func(10); // 10

//

function func(a = 55) { 
  a = 99; // updating a does not also update arguments[0]
  console.log(arguments[0]);
}
func(10); // 10


function func(a = 55) { 
  console.log(arguments[0]);
}
func(); // undefined
Copy after login

Implementation of JS variable parameters 2: rest parameter (...)

The rest parameter was introduced in the ES6 standard (The form is

...variable name), used to obtain the extra parameters of the function. The variable matched with the rest parameter is an array, which puts the extra parameters into the array. Very suitable for dealing with variable length parameters.

Rest is to solve the problem of the inconsistency in the number of parameters passed in. It means accepting the extra parameters and putting them into an array; the Rest parameters themselves are arrays, and all array-related methods can be used.

Implementation syntax of variable parameters:

function f(a, b, ...theArgs) {
  // ...
}
Copy after login

  • theArgs starts with "...", it is an array, and its value comes from The actual caller passes in [0, theArgs.length) (index range: 0 to theArgs.length-1)

Note: There cannot be any other parameters after the rest parameter (that is, it can only be the last parameter), otherwise an error will be reported.

function f(arg1, ...rest, arg2) { // arg2 after ...rest ?!
  // error
}
Copy after login

Detailed explanation of how JavaScript functions implement variable parameters? (Summary sharing)

Distinguish between rest parameters and parameter (arguments) objects

  • rest parameters will not be used for each The variable is given a separate name, and the parameter object contains all the parameters passed to the function

  • The parameter object is not a real array, and the rest parameter is a real array instance. For example, array sort, map, forEach, and pop methods can be used directly

  • The parameter object has its own additional characteristics (such as the callee attribute)

Rest参数的引入减少样式代码

//以前函数
function f(a, b) {
  var args = Array.prototype.slice.call(arguments, f.length);
 
  // …
}
 
// 等效于现在
 
function f(a, b, ...args) {
  
}
Copy after login

Rest参数可以被解构(通俗一点,将rest参数的数据解析后一一对应)不要忘记参数用[] 括起来,因为它数组嘛

function f(...[a, b, c]) {
  return a + b + c;
}
 
f(1)          //NaN 因为只传递一个值,其实需要三个值
f(1, 2, 3)    // 6
f(1, 2, 3, 4) // 6 (第四值没有与之对应的变量名)
Copy after login

示例

1、计算参数和

function sumAll(...args) { // args 是数组的名称
  let sum = 0;
 
  for (let arg of args) sum += arg;
 
  return sum;
}
 
console.log( sumAll(1) ); // 1
console.log( sumAll(1, 2) ); // 3
console.log( sumAll(1, 2, 3) ); // 6
Copy after login

Detailed explanation of how JavaScript functions implement variable parameters? (Summary sharing)

2、每个参数乘以2

function multiply(multiplier, ...theArgs) {
  return theArgs.map(function(element) {
    return multiplier * element;
  });
}
 
var arr = multiply(2, 1, 2, 3); 
console.log(arr); // [2, 4, 6]
Copy after login

Detailed explanation of how JavaScript functions implement variable parameters? (Summary sharing)

3、排序

function sortRestArgs(...theArgs) {
  var sortedArgs = theArgs.sort();
  return sortedArgs;
}
//好像一位和两位混合不能进行排序,这需要看一下为甚?主要第一个为主
console.log(sortRestArgs(5, 3, 7, 1)); // shows 1, 3, 5, 7
Copy after login

Detailed explanation of how JavaScript functions implement variable parameters? (Summary sharing)

对比:参数对象arguments不能排序

function sortArguments() {
  //arguments是参数对象不能直接使用sort()方法,因为不是数组实例,需要转换
  var sortedArgs = arguments.sort(); 
  return sortedArgs; // this will never happen
}
 
// 会抛出类型异常,arguments.sort不是函数
console.log(sortArguments(5, 3, 7, 1));
Copy after login

Detailed explanation of how JavaScript functions implement variable parameters? (Summary sharing)

【相关推荐:javascript学习教程 、编程视频

The above is the detailed content of Detailed explanation of how JavaScript functions implement variable parameters? (Summary sharing). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

Can golang variable parameters be used in generic functions? Can golang variable parameters be used in generic functions? Apr 29, 2024 pm 02:06 PM

In Go, variable parameters can be used for generic functions, allowing the creation of generic functions that accept a variable number of parameters and are suitable for multiple types. For example, you can create a generic function Mode that finds the most frequently occurring element in a given list: Mode accepts a variable number of elements of type T. It counts elements by creating counts for each element. Then it finds the element that appears the most and returns it as mode. In the main function, you can call the Mode function for the list of strings and the list of integers, which will return the string and number with the most occurrences respectively.

See all articles