gpt4 book ai didi

通过引用或值传递的 JavaScript 数组?

转载 作者:行者123 更新时间:2023-11-30 12:39:35 25 4
gpt4 key购买 nike

我对数组在传递给函数时的处理方式有些困惑。我的问题是为什么 sample2.js 的输出不为空?

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

最佳答案

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

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

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

您没有按照引用然后将 null 分配给数组所在的内存空间。

关于通过引用或值传递的 JavaScript 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24933082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com