Home Web Front-end JS Tutorial Pass parameters by value in js function

Pass parameters by value in js function

Jan 18, 2018 pm 02:43 PM
javascript transfer parameter

This article mainly shares with you an example of passing parameters by value in a js function. It has a very good reference value. Let’s follow the editor to have a look. I hope it will be helpful to everyone. I hope it can help everyone.

JS function parameters are passed by value. Under normal circumstances, changing the value of the function parameter will not affect the variables outside the function. For example:

'use strict';
var list = [1, 2, 3];
list.forEach(function(item) {
 item ++;
});
console.log(list); // [ 1, 2, 3 ]
Copy after login

This is because when the js function receives parameters, it will generate a copy variable, which is equal to the value of the parameter. You can analyze how js runs like this:

'use strict';
var list = [1, 2, 3];
list.forEach(function(item, i) {
 // 第一个item是副本,第二个item是数组元素list[i]
 var item = item;
 // 副本item++
 item ++;
 // 打印的是副本的值
 console.log(item); // 2, 3, 4
});
// 原数组不会改变
console.log(list); // [ 1, 2, 3 ]
Copy after login

But when Is an object passed as the parameter of the function?

'use strict';var list = [{a: 1, b: 2}];
list.forEach(function(item) {
 item.a ++;
});
console.log(list); // [ { a: 2, b: 2 } ]
Copy after login

I found that the value of the external variable of the function was actually changed inside the function, so why is this?

Let’s analyze how js runs this code

'use strict';
var list = [{a: 1, b: 2}];
list.forEach(function(item, i) {
 // 第一个item是副本,第二个item是数组元素list[i]
 var item = item;
 // 此时item和list[i]指向的是同一地址,故两者完全一样
 console.log(item === list[i]); // true
 // 此时item.a++ 亦即 list[i].a++
 item.a ++;
 // list[i]的值已经改变
 console.log(list[i]); // { a: 2, b: 2 }
});
console.log(list); // [ { a: 2, b: 2 } ]
Copy after login

So why does this happen?

Since objects in js are reference types, the step of var item = item is equivalent to assigning the address of list[i] to item. Both of them point to the address of the original object, so through When one modifies a value, it actually modifies the object they point to. In the example, the value of the original object is changed through the item.a++ method, so [ { a: 2, b: 2 } ] should be output in the end.

Related recommendations:

htmlHow to pass parameters when page jumps

php reference definition and reference passing parameter examples Detailed explanation of usage

#Detailed explanation of basic syntax of php function and usage examples of passing parameters

The above is the detailed content of Pass parameters by value in js function. 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

Video Face Swap

Video Face Swap

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

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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

i9-12900H parameter evaluation list i9-12900H parameter evaluation list Feb 23, 2024 am 09:25 AM

i9-12900H is a 14-core processor. The architecture and technology used are all new, and the threads are also very high. The overall work is excellent, and some parameters have been improved. It is particularly comprehensive and can bring users Excellent experience. i9-12900H parameter evaluation review: 1. i9-12900H is a 14-core processor, which adopts the q1 architecture and 24576kb process technology, and has been upgraded to 20 threads. 2. The maximum CPU frequency is 1.80! 5.00ghz, which mainly depends on the workload. 3. Compared with the price, it is very suitable. The price-performance ratio is very good, and it is very suitable for some partners who need normal use. i9-12900H parameter evaluation and performance running scores

C++ function parameter type safety check C++ function parameter type safety check Apr 19, 2024 pm 12:00 PM

C++ parameter type safety checking ensures that functions only accept values ​​of expected types through compile-time checks, run-time checks, and static assertions, preventing unexpected behavior and program crashes: Compile-time type checking: The compiler checks type compatibility. Runtime type checking: Use dynamic_cast to check type compatibility, and throw an exception if there is no match. Static assertion: Assert type conditions at compile time.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Advanced usage of reference parameters and pointer parameters in C++ functions Advanced usage of reference parameters and pointer parameters in C++ functions Apr 21, 2024 am 09:39 AM

Reference parameters in C++ functions (essentially variable aliases, modifying the reference modifies the original variable) and pointer parameters (storing the memory address of the original variable, modifying the variable by dereferencing the pointer) have different usages when passing and modifying variables. Reference parameters are often used to modify original variables (especially large structures) to avoid copy overhead when passed to constructors or assignment operators. Pointer parameters are used to flexibly point to memory locations, implement dynamic data structures, or pass null pointers to represent optional parameters.

Parameters of vlookup function and explanation of their meanings Parameters of vlookup function and explanation of their meanings Jan 09, 2024 pm 03:18 PM

We must have used the vlookup function when using excel. So there are several such functions, and how each function is used. As far as the editor knows, there are four vlookup functions, namely Lookup_value, Table_array, col_index_num, and Range_lookup. So let me tell you their specific usage~ The vlookup function has several parameters and the meaning of each parameter. The parameters of the vlookup function include Lookup_value, Table_array, col_index_num, and Range_lookup, a total of 4. 1.Lookup

See all articles