You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 8中如何通过方法修改引用类型参数的值?

如何在TypeScript中通过函数修改外部数组变量的值

你遇到的问题核心是TypeScript的参数传递规则:函数参数采用按值传递。虽然数组属于引用类型,但你在callSomeMethod里直接给data赋值了新数组,这会让参数data的引用指向新的内存地址,而外部的test变量依然指向最初的空数组引用,所以函数执行完后test还是空的。

下面是几种可行的解决方法:

方案一:修改原数组内容(不替换整个数组)

直接操作原数组的元素,保持数组引用不变,外部变量就能同步看到修改后的内容:

callSomeMethod(data: CommonModel[]) {
  // 清空原数组
  data.length = 0;
  // 添加新元素
  data.push({ name: 'testing' });
  console.log('data:', data);
}

testRef() {
  let test: CommonModel[] = [];
  this.callSomeMethod(test);
  console.log('test:', test); // 输出 [{ name: 'testing' }]
}

方案二:让函数返回新数组,外部变量接收返回值

放弃修改原数组,改为让函数生成新数组并返回,外部变量重新赋值:

callSomeMethod(): CommonModel[] {
  let test2: CommonModel[] = [{ name: 'testing' }];
  console.log('data:', test2);
  return test2;
}

testRef() {
  let test: CommonModel[] = [];
  test = this.callSomeMethod(); // 接收返回的新数组
  console.log('test:', test); // 输出 [{ name: 'testing' }]
}

方案三:用对象包装数组,传递对象引用

把数组放在一个对象的属性中,传递这个对象。因为对象是引用类型,修改对象的属性会直接影响外部的对象实例:

callSomeMethod(wrapper: { data: CommonModel[] }) {
  wrapper.data = [{ name: 'testing' }];
  console.log('data:', wrapper.data);
}

testRef() {
  let testWrapper = { data: [] as CommonModel[] };
  this.callSomeMethod(testWrapper);
  console.log('test:', testWrapper.data); // 输出 [{ name: 'testing' }]
}

内容的提问来源于stack exchange,提问作者user3011414

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 18:35:27