search
HomeWeb Front-endFront-end Q&ADoes javascript support variable length parameters?

Javascript supports variable length parameters. Two methods to implement variable-length parameters: 1. Use the arguments object. The length of the arguments object is determined by the number of actual parameters rather than the number of formal parameters; when both arguments and values ​​exist, the two values ​​are synchronized. , but for one of the null cases, the value will not be synchronized for this null case. 2. Rest parameter means accepting redundant parameters and putting them into an array. The syntax is "...variable name".

Does javascript support variable length parameters?

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

Javascript supports variable length parameters.

Implementation of JS variable length parameters (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>
  • 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:

Does javascript support variable length parameters?

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]

Parameters can also be set:

arguments[0] = 'value';

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]; // 方式二

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

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

In ES6 standard The rest parameter (in the form

...variable name) is introduced in to obtain the redundant 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) {
  // ...
}

  • 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
}

Does javascript support variable length parameters?

Distinguish between rest parameters and parameter (arguments) objects

  • rest参数不会为每个变量给一个单独的名称,参数对象包含所有参数传递给函数

  • 参数对象不是真正的数组,rest参数是真实的数组实例。例如数组sort、map、forEach、pop的方法都可以直接使用

  • 参数对象有他自己额外的特性(例如callee 属性)

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

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

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 (第四值没有与之对应的变量名)

示例

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

Does javascript support variable length parameters?

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]

Does javascript support variable length parameters?

3、排序

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

Does javascript support variable length parameters?

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

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

Does javascript support variable length parameters?

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

The above is the detailed content of Does javascript support variable length parameters?. 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
React: The Foundation for Modern Frontend DevelopmentReact: The Foundation for Modern Frontend DevelopmentApr 19, 2025 am 12:23 AM

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

The Future of React: Trends and Innovations in Web DevelopmentThe Future of React: Trends and Innovations in Web DevelopmentApr 19, 2025 am 12:22 AM

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

React: A Powerful Tool for Building UI ComponentsReact: A Powerful Tool for Building UI ComponentsApr 19, 2025 am 12:22 AM

React is a JavaScript library for building user interfaces. Its core idea is to build UI through componentization. 1. Components are the basic unit of React, encapsulating UI logic and styles. 2. Virtual DOM and state management are the key to component work, and state is updated through setState. 3. The life cycle includes three stages: mount, update and uninstall. The performance can be optimized using reasonably. 4. Use useState and ContextAPI to manage state, improve component reusability and global state management. 5. Common errors include improper status updates and performance issues, which can be debugged through ReactDevTools. 6. Performance optimization suggestions include using memo, avoiding unnecessary re-rendering, and using us

Using React with HTML: Rendering Components and DataUsing React with HTML: Rendering Components and DataApr 19, 2025 am 12:19 AM

Using HTML to render components and data in React can be achieved through the following steps: Using JSX syntax: React uses JSX syntax to embed HTML structures into JavaScript code, and operates the DOM after compilation. Components are combined with HTML: React components pass data through props and dynamically generate HTML content, such as. Data flow management: React's data flow is one-way, passed from the parent component to the child component, ensuring that the data flow is controllable, such as App components passing name to Greeting. Basic usage example: Use map function to render a list, you need to add a key attribute, such as rendering a fruit list. Advanced usage example: Use the useState hook to manage state and implement dynamics

React's Purpose: Building Single-Page Applications (SPAs)React's Purpose: Building Single-Page Applications (SPAs)Apr 19, 2025 am 12:06 AM

React is the preferred tool for building single-page applications (SPAs) because it provides efficient and flexible ways to build user interfaces. 1) Component development: Split complex UI into independent and reusable parts to improve maintainability and reusability. 2) Virtual DOM: Optimize rendering performance by comparing the differences between virtual DOM and actual DOM. 3) State management: manage data flow through state and attributes to ensure data consistency and predictability.

React: The Power of a JavaScript Library for Web DevelopmentReact: The Power of a JavaScript Library for Web DevelopmentApr 18, 2025 am 12:25 AM

React is a JavaScript library developed by Meta for building user interfaces, with its core being component development and virtual DOM technology. 1. Component and state management: React manages state through components (functions or classes) and Hooks (such as useState), improving code reusability and maintenance. 2. Virtual DOM and performance optimization: Through virtual DOM, React efficiently updates the real DOM to improve performance. 3. Life cycle and Hooks: Hooks (such as useEffect) allow function components to manage life cycles and perform side-effect operations. 4. Usage example: From basic HelloWorld components to advanced global state management (useContext and

React's Ecosystem: Libraries, Tools, and Best PracticesReact's Ecosystem: Libraries, Tools, and Best PracticesApr 18, 2025 am 12:23 AM

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

React and Frontend Development: A Comprehensive OverviewReact and Frontend Development: A Comprehensive OverviewApr 18, 2025 am 12:23 AM

React is a JavaScript library developed by Facebook for building user interfaces. 1. It adopts componentized and virtual DOM technology to improve the efficiency and performance of UI development. 2. The core concepts of React include componentization, state management (such as useState and useEffect) and the working principle of virtual DOM. 3. In practical applications, React supports from basic component rendering to advanced asynchronous data processing. 4. Common errors such as forgetting to add key attributes or incorrect status updates can be debugged through ReactDevTools and logs. 5. Performance optimization and best practices include using React.memo, code segmentation and keeping code readable and maintaining dependability

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.