JavaScript数组是按引用传递还是按值传递?

3

我对数组在传递到函数时如何处理有些困惑。我的问题是为什么 sample2.js 的输出结果不是 null?

// sample1.js======================================
// This clearly demonstrates that the array was passed by reference
function foo(o) {
  o[1] = 100;
}

var myArray = [1,2,3];
console.log(myArray);  // o/p : [1,2,3]
foo(myArray);
console.log(myArray); // o/p : [1,100,3]




//sample2.js =====================================
// upon return from bar, myArray2 is not set to null.. why so
function bar(o) {
  o = null;
}

var myArray2 = [1,2,3];
console.log(myArray2);  // o/p : [1,2,3]
bar(myArray2);
console.log(myArray2); // o/p : [1,100,3]

通过引用传递。只有基本类型按值传递。 - Alex
2个回答

9

指向数组的变量只包含引用。这些引用被复制。

bar中,omyArray2都是对同一数组的引用。o不是对myArray2变量的引用。

在函数内部,您正在使用新值(null)覆盖o(一个对数组的引用)的值。

您没有跟随引用,然后将null分配给数组存在的内存空间。


0
一个视觉化的例子,解释了Quentin多年前所说的话。换句话说,对数组的引用会创建新的数组,但新的数组包含对原始数组值的引用。

function updateArray (arrayOfRefs) {
      let arrayInternal = arrayOfRefs;
      arrayInternal[1] = 100;  // or a value like null
      arrayInternal = null;  // null this reference array (not the external original)
      arrayOfRefs[1] -= 1;  // proves both refs were to same external value
      arrayOfRefs[2] = null;
}

var externalArray = [1,2,3];  console.log(externalArray);
updateArray (externalArray);  console.log(externalArray);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接