我有一個問題...thant是一個代碼:
class Currency {
cosnstructor() {
this.currencyInfo = [];
}
getCurrency(getInfo) {
this.currencyInfo = getInfo;
}
}
const actuallyCurrency = new Currency;
(async () => {
const response = await fetch(`http://api.nbp.pl/api/exchangerates/tables/A`);
const data = await response.json();
const currency = data[0].rates;
currency.map(element => curArr.push(element));
})();
const curArr = [];
actuallyCurrency.getCurrency(curArr);
這段代碼運行良好,但我需要在 this.currencyInfo 中創建一個新陣列,而不是參考陣列 curArr。
uj5u.com熱心網友回復:
我這就是你想要的:
class Currency {
constructor() {
this.currencyInfo = [];
}
getCurrency(getInfo) {
this.currencyInfo = [...getInfo]; // <-- change this line
}
}
const actuallyCurrency = new Currency;
(async () => {
const response = { json: () => { return [{rates:{a:1, b:2, c:3}}];}};
// const response = await fetch(`http://api.nbp.pl/api/exchangerates/tables/A`);
const data = await response.json();
const currency = data[0].rates;
for(key in currency) curArr.push(currency[key]);
actuallyCurrency.getCurrency(curArr);
console.log(actuallyCurrency.currencyInfo);
})();
const curArr = [];
有一點需要你理解:
1-...是一個對其引數進行淺拷貝的運算子。因此,如上所述使用您將在currencyInfo 中獲得一個新陣列。
2-為什么actuallyCurrency.getCurrency(curArr); console.log(actuallyCurrency.currencyInfo);必須在函式內部?
因為 os 操作的異步性質。異步被推遲到執行完成時執行,因此在填充 curArr 之前實際到達了Currency.getCurrency(curArr)。這使得內部 currencyInfo 陣列為空,并且在執行后不會再次填充。
3-為什么這currency.map(element => curArr.push(element));不起作用?
因為貨幣是一個物件,而不是一個可迭代的陣列。如果你想迭代一個物件的元素,你必須選擇:將它的鍵作為一個陣列,迭代這個陣列,然后使用它的鍵或使用 for...in 來獲取值,就像我做的那樣。
希望這已經足夠了。隨意問你想問的任何問題
uj5u.com熱心網友回復:
下一個麻煩...嘗試了一個:
getCurrency(getInfo) {
this.currencyInfo = getInfo.concat();
}
我嘗試了你的想法,但我的建構式中的陣列仍然是空的
影像
uj5u.com熱心網友回復:
有一些改進需要做。可能最重要的是安排currencyInfo 在 fetch 完成后檢查實體變數。評論中指出的這個和其他建議......
class Currency {
cosnstructor() {
this.currencyInfo = [];
}
// methods that assign (and don't return anything) ought to be called "set" something
setCurrency(array) {
this.currencyInfo = array;
}
// it probably makes sense to have this class do it's own async initialization
async fetchCurrency() {
const url = `http://api.nbp.pl/api/exchangerates/tables/A`;
// try/catch, so we can respond to failures
try {
const response = await fetch(url);
const data = await response.json();
// no need to map and not sure why the array needs to be copied. I suspect
// it doesn't but [...array] copies array
this.setCurrency([...data[0].rates]);
} catch (error) {
console.log('error fetching', error);
}
}
}
// instantiation requires ()
const actuallyCurrency = new Currency();
// no async/await at the top level
actuallyCurrency.fetchCurrency().then(() => {
console.log(actuallyCurrency.currencyInfo);
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/531001.html
下一篇:如何使用陣列資料驗證值?
