为什么某些操作不会更改传递给函数的数组? [英] Why do some operations not alter an array that was passed to a function?
问题描述
场景1:
var myArray = [2, 3, 4, 5];
function doStuff(arr) {
arr = [];
}
doStuff(myArray);
console.log(myArray); // [2,3,4,5]
方案2:
var myArray = [2, 3, 4, 5];
function doStuff(arr) {
arr.pop();
}
doStuff(myArray);
console.log(myArray); // [2,3,4]
为什么方案1 没有更新全局声明的数组,但是方案2 可以吗?
Why does scenario 1 not update the globally declared array but scenario 2 does?
推荐答案
在第一个示例中:
您正在更改变量 arr
,该变量仅持有对数组<$的引用c $ c> [2,3,4,5] ,所以不要持有对 [2,3,4,5]
的引用,它将保存对另一个数组 []
的引用。
You are altering the variable arr
which is merely just holding a reference to the array [2, 3, 4, 5]
, so instead of holding a reference to [2, 3, 4, 5]
, it will hold a reference to another array []
.
在 var行myArray = [2,3,4,5];
:
myArray -----------------------------------> [2, 3, 4, 5]
然后在 doStuff( myArray);
:
myArray -----------------------------------> [2, 3, 4, 5]
↑
arr ----------------------------------------------/
然后在该行 arr = [];
:
myArray -----------------------------------> [2, 3, 4, 5]
arr ---------------------------------------> []
=> 因此,在调用<$ c $之后c> doStuff , myArray
仍为 [2、3、4、5]
。
=> So, after the call to doStuff
, myArray
is still [2, 3, 4, 5]
.
在第二个示例中:
您正在使用对 arr
中存储的 [2、3、4、5]
的引用调用函数 pop
对其进行更改。
You are using the reference to [2, 3, 4, 5]
stored in arr
to call a function pop
on it that alters it.
在 var myArray行= [2,3,4,5];
:
myArray -----------------------------------> [2, 3, 4, 5]
然后在 doStuff( myArray);
:
myArray -----------------------------------> [2, 3, 4, 5]
↑
arr ----------------------------------------------/
然后在该行 arr.pop();
:
myArray -----------------------------------> [2, 3, 4, 5].pop()
↑
arr.pop() ----------------------------------------/
数组到:
myArray -----------------------------------> [2, 3, 4]
↑
arr ----------------------------------------------/
=> 因此,在调用 doStuff
之后, myArray
现在为 [2、3、4]
。
=> So, after the call to doStuff
, myArray
is now [2, 3, 4]
.
这篇关于为什么某些操作不会更改传递给函数的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!