如何将for循环中的变量插入到变量调用中

huangapple go评论78阅读模式
英文:

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 &lt;double&gt; closingPricesBTC = [];
    List &lt;double&gt; closingPricesETH = [];
    List &lt;double&gt; closingPricesLTC = [];

        for (String cryptoCurrency in cryptoAbbreviation){
        .
        . (some code)
        .
        double closePrice = ....

        closingPrices.add(closePrice);
        }

}

where cryptoAbbreviation is

const List&lt;String&gt; cryptoAbbreviation = [&#39;BTC&#39;, &#39;ETH&#39;, &#39;LTC&#39;];

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&lt;String, List&lt;double&gt;&gt; closingPrices = {&#39;BTC&#39;:[], &#39;ETH&#39;:[], &#39;LTC&#39;:[]};


        for (String cryptoCurrency in cryptoAbbreviation){
        .
        . (some code)
        .
        double closePrice = ....

        closingPrices[cryptoCurrency].add(closePrice);
        }

huangapple
  • 本文由 发表于 2020年10月24日 22:49:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/64514638.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定