TypeScript中如何更新数组指定位置的元素?
更新数组指定索引元素的方法
要更新你创建的数组中第n个元素的数据,直接通过数组下标访问操作即可,分两种场景:
1. 修改元素对象的单个字段
如果只需要更新某个字段的值,直接定位下标后给对应字段赋值(注意数组索引从0开始):
// n为目标元素的索引 this.array[n].field1 = '更新后的test值'; this.array[n].field2 = '更新后的field2内容';
2. 替换整个元素对象
如果需要把目标元素替换成一个全新的对象:
this.array[n] = { field1: '新的field1值', field2: '新的field2值' };
针对你初始化代码的注意点
你当前的循环初始化逻辑存在闭包陷阱:subscribe的异步回调里引用的this.j会在循环结束后统一变成this.accNum,导致所有回调最终都修改数组的最后一个元素。
可以用以下两种方式修复:
方式一:使用局部循环变量(推荐)
用let声明循环变量,为每次循环绑定独立的作用域:
for(let j = 0; j < this.accNum; j++) { this.array.push({ field1:'test1', field2:'' }); this.http1 .get(this.url.concat(this.array[j]?.field1)) .subscribe((response1: any) => { // 这里的j是当前循环的独立变量,不会被后续循环覆盖 this.array[j].field2 = 'test2'; // 实际场景中可以用接口返回值赋值:this.array[j].field2 = response1.data; }); }
方式二:用立即执行函数保存索引
通过IIFE把当前循环的索引值固化到回调作用域中:
for(this.j = 0; this.j < this.accNum; this.j++) { this.array.push({ field1:'test1', field2:'' }); const currentIdx = this.j; // 用call绑定this上下文,传递当前索引 (function(idx) { this.http1 .get(this.url.concat(this.array[idx]?.field1)) .subscribe((response1: any) => { this.array[idx].field2 = 'test2'; }); }).call(this, currentIdx); }
内容的提问来源于stack exchange,提问作者user19938599
相关产品推荐
相关产品推荐

