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

异步Fetch场景下JavaScript类中数组避免引用传递的问题

解决方案

首先修正代码里的拼写错误:cosnstructor 必须改为 constructor,否则类实例化会失败。

要让this.currencyInfo成为独立的新数组,核心是复制传入的数组,而不是直接赋值引用。以下是几种简单可行的方式:

方法1:使用展开运算符(推荐,语法简洁)

修改Currency类的getCurrency方法:

class Currency {
    constructor() {
        this.currencyInfo = [];
    }

    getCurrency(getInfo) {
        // 复制传入的数组,创建新引用
        this.currencyInfo = [...getInfo];
    }    
}

方法2:使用Array.from()

getCurrency(getInfo) {
    this.currencyInfo = Array.from(getInfo);
}

方法3:使用数组的slice()方法

getCurrency(getInfo) {
    // slice()不传参数时会返回原数组的浅拷贝
    this.currencyInfo = getInfo.slice();
}

额外优化建议

  1. 调整变量声明顺序:把const curArr = [];移到async自执行函数前面,符合先声明后使用的规范:
const curArr = [];

(async () => {
    const response = await fetch(`http://api.nbp.pl/api/exchangerates/tables/A`);
    const data = await response.json();
    const currency = data[0].rates; 
    curArr.push(...currency); // 用展开运算符一次性添加所有元素,比map+push更高效
})();
  1. 替换不必要的map调用:原代码里用map只是为了遍历push元素,这不符合map的设计初衷(map用于转换数组并返回新数组),改用push(...currency)或者forEach更合适。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 03:01:08