Home >Web Front-end >JS Tutorial >Pass parameters by value in js function
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 ]
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 ]
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 } ]
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 } ]
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!