英文:
How to Insert For In Loop Variable into Variable Call
问题
class GraphData {
List<double> closingPricesBTC = [];
List<double> closingPricesETH = [];
List<double> closingPricesLTC = [];
for (String cryptoCurrency in cryptoAbbreviation) {
// ...
double closePrice = /* some code */;
if (cryptoCurrency == 'BTC') {
closingPricesBTC.add(closePrice);
} else if (cryptoCurrency == 'ETH') {
closingPricesETH.add(closePrice);
} else if (cryptoCurrency == 'LTC') {
closingPricesLTC.add(closePrice);
}
}
}
其中cryptoAbbreviation
为:
const List<String> cryptoAbbreviation = ['BTC', 'ETH', 'LTC'];
我尝试过使用 closingPrices$cryptoCurrency.add(closePrice);
但是这种方式不起作用。
英文:
class GraphData {
List <double> closingPricesBTC = [];
List <double> closingPricesETH = [];
List <double> closingPricesLTC = [];
for (String cryptoCurrency in cryptoAbbreviation){
.
. (some code)
.
double closePrice = ....
closingPrices.add(closePrice);
}
}
where cryptoAbbreviation is
const List<String> cryptoAbbreviation = ['BTC', 'ETH', 'LTC'];
How can I append the current "cryptocurrency" String into the name of the variable for closingPrices.add(closePrice)
so that I can end up with closingPricesBTC.add(closePrice)
, closingPricesETH.add(closePrice)
, and closingPricesLTC.add(closePrice)
I've tried closingPrices$cryptoCurrency.add(closePrice);
but that doesn't work.
答案1
得分: 1
你无法生成变量名,但可以尝试使用 HashMap(Java)/Map(Dart)。这应该满足您的要求。
Map<String, List<Double>> closingPrices = {'BTC': [], 'ETH': [], 'LTC': []};
for (String cryptoCurrency : cryptoAbbreviation) {
// ...
// (一些代码)
// ...
double closePrice = ...;
closingPrices.get(cryptoCurrency).add(closePrice);
}
注意:上述翻译中的代码片段是基于 Java 语言的。如果您需要 Dart 语言的翻译,请告知我。
英文:
You can't generate variable names but you can try HashMap(Java)/Map(Dart). This should fulfill your requirement.
Map<String, List<double>> closingPrices = {'BTC':[], 'ETH':[], 'LTC':[]};
for (String cryptoCurrency in cryptoAbbreviation){
.
. (some code)
.
double closePrice = ....
closingPrices[cryptoCurrency].add(closePrice);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论