【问题标题】:How do I log the name of the variable instead of the data associated with it?如何记录变量的名称而不是与其关联的数据?
【发布时间】:2021-03-17 05:18:24
【问题描述】:

我正在 node.js 上构建一个程序来扫描某些货币的价格,并且我正在获取价格,但是我希望该程序也记录货币的名称,而不仅仅是价格。正如您在以下代码中看到的,console.log 中的“货币”变量是我尝试在记录价格之前显示名称。

    const currencies = [euro, yen];
    for (let currency of currencies) {    
        const pair = await fetchPairData(currency, dollar);
        const route = new Route([pair], dollar);
        console.log(currency + route.midPrice.toSignificant(6));
        }

但货币变量似乎想要返回与其关联的值,而不是货币的名称......我该如何切换? 谢谢大家的帮助,我会一步一步做好的!

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    只要你这样做:

    const currencies = [euro, yen];
    

    没有从currencies[0] 回到euro 或从currencies[1] 回到yen 的没有链接。 [euro, yen] 获取euro 和yen 变量的值,并将这些值放入数组中。

    尝试对现有内容进行最小的更改,您可以使用对象而不是数组:

    for (let [currencyName, currencyValue] of Object.entries({euro, yen})) {    
        const pair = await fetchPairData(currencyValue, dollar);
        const route = new Route([pair], dollar);
        console.log(currencyName, currencyValue + route.midPrice.toSignificant(6));
    }
    

    工作原理:

    • {euro, yen} 是使用速记属性表示法的对象字面量;速记是{euro: euro, yen: yen}。因此,您最终会得到一个对象,其属性名为 "euro" 和 "yen",其值来自 euro 和 yen 变量。
    • Object.entries 从对象自己的可枚举属性创建一个 [name, value] 对数组。数组最终是:
      [ ["euro", euroValue], ["yen", yenValue] ]
      
      (当然,您可以直接执行此操作,而不是通过 Object.entries({euro, yen})。)
    • for-of 循环遍历该数组中的条目。
    • 我在for-of 中使用解构赋值将名称和值获取到单独的常量中。

    但是,理想情况下,您应该更改起点,以便从名称(货币)和值(货币值)对开始,而不是根据变量名称创建它们.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多