如果我在myArray中变异了myFunction的值,那么将更新新的myArray:
let myArray = [1, 2, 3];
console.log( JSON.stringify(myArray) ); // [1, 2, 3]
function myFunction(arr) {
arr.push(4);
console.log( JSON.stringify(arr) ); // [1, 2, 3, 4]
return arr;
}
myFunction(myArray);
console.log( JSON.stringify(myArray) ); // [1, 2, 3, 4].as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}
但是,如果我试图在myArray中使用arr = [0];重新分配myFunction,则myArray将保持不变。
let myArray = [1, 2, 3];
console.log( JSON.stringify(myArray) );; // [1, 2, 3]
function myFunction(arr) {
arr = [0];
console.log( JSON.stringify(arr) ); // [0]
return arr;
}
myFunction(myArray);
console.log( JSON.stringify(myArray) ); // [1, 2, 3].as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}
为什么不能在上面的示例中重新分配myArray,但如果我这样做可以:
let myArray = [1, 2, 3];
myArray = [0];
console.log(myArray); // [0]发布于 2022-06-21 13:54:58
将链接到数组内部元素的寻址与数组本身的寻址混淆在一起。
let myArray = [1, 2, 3]; 在内存中使用[1, 2, 3]创建数组对象
并在myArray变量上给出他的地址
function myFunction(arr)创建一个名为arr的新变量
带有myArray变量地址的副本
以同样的方式:
let myArray = [1, 2, 3]
let arr = myArray
arr = [0]
console.log( JSON.stringify(myArray) ) // [1, 2, 3]
console.log( JSON.stringify(arr) ) // [0] .as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}
发布于 2022-06-21 13:36:51
在您的示例中,您实际上并没有重新分配myArray。你需要做myArray = myFunction(myArray)。
https://stackoverflow.com/questions/72701717
复制相似问题