首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用数组引用传递

用数组引用传递
EN

Stack Overflow用户
提问于 2022-06-21 13:32:27
回答 2查看 41关注 0票数 1

如果我在myArray中变异了myFunction的值,那么将更新新的myArray

代码语言:javascript
复制
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]
代码语言:javascript
复制
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}

但是,如果我试图在myArray中使用arr = [0];重新分配myFunction,则myArray将保持不变。

代码语言:javascript
复制
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]
代码语言:javascript
复制
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}

为什么不能在上面的示例中重新分配myArray,但如果我这样做可以:

代码语言:javascript
复制
let myArray = [1, 2, 3];
myArray = [0];
console.log(myArray); // [0]
EN

回答 2

Stack Overflow用户

发布于 2022-06-21 13:54:58

将链接到数组内部元素的寻址与数组本身的寻址混淆在一起。

代码语言:javascript
复制
let myArray = [1, 2, 3];  

在内存中使用[1, 2, 3]创建数组对象

并在myArray变量上给出他的地址

代码语言:javascript
复制
function myFunction(arr)

创建一个名为arr的新变量

带有myArray变量地址的副本

以同样的方式:

代码语言:javascript
复制
let myArray = [1, 2, 3]
let arr     = myArray

arr = [0]
 
console.log( JSON.stringify(myArray) ) // [1, 2, 3]
console.log( JSON.stringify(arr) )     // [0] 
代码语言:javascript
复制
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}

票数 0
EN

Stack Overflow用户

发布于 2022-06-21 13:36:51

在您的示例中,您实际上并没有重新分配myArray。你需要做myArray = myFunction(myArray)

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72701717

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档