异步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(); }
额外优化建议
- 调整变量声明顺序:把
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更高效 })();
- 替换不必要的
map调用:原代码里用map只是为了遍历push元素,这不符合map的设计初衷(map用于转换数组并返回新数组),改用push(...currency)或者forEach更合适。
内容的提问来源于stack exchange,提问作者Dany King
相关产品推荐
相关产品推荐

