【问题标题】:How to compare previous value of variable with new variable value on each response node.js如何在每个响应 node.js 上将变量的先前值与新变量值进行比较
【发布时间】:2021-09-14 01:18:26
【问题描述】:

我正在运行 cron,它每 30 秒检查一次价格,并将返回一个资产价值。 如果价格与以前的价格不同,我想记录它。我正在测试它,因为这对我未来的想法非常有用...price 变量持有价格。我的目标是在变量不同时执行一些操作。

   //Stuff above the code like cron and general discord client.on ↑

   //this will log current price of asset
   console.log(price, 'PRICE UPDATED!')
    // tried to compare price however this is unsucessful, as it doesn't do anything...
    var Previousprice = null;
    function foo() {
      var Currentprice = $(price.toFixed(2))
      if (Previousprice == Currentprice) {
        $(price.toFixed(2))
        console.log('Price is same!')
      }
      Previousprice = Currentprice
      console.log('Price has changed!')
      //new discord action...
    }
   });
  });
 });
});

到目前为止,我也尝试过这个,但我认为这完全没用,不会那样工作......

    console.log(price, 'PRICE UPDATED!')
    let Previousprice = null;
    let Currentprice = price
    if (price) {
      let Previousprice = price.toFixed(2)
      console.log(price, 'Price defined')
    } else if(Previousprice === Currentprice) {
      console.log(price, 'Price is same') 
    } else if(Previousprice !== Currentprice) {
      let Previousprice = price.toFixed(2)
      console.log(price, 'Price changed!')  
    }
Logs: 
1.29739982471208 PRICE UPDATED!
1.29739982471208 Price defined
1.29739982471208 PRICE UPDATED!
1.29739982471208 Price defined
1.29660532105896 PRICE UPDATED!
1.29660532105896 Price defined

【问题讨论】:

    标签: node.js variables request discord.js compare


    【解决方案1】:

    您正在重新声明和分配 previousPrice = null;每 30 秒。如果没有看到周围的代码,就无法为您提供具体信息,但您通常想要的是一个像 currentPrice 这样的全局变量,在应用程序首次运行时初始化为 0。像这样的东西应该可以工作:

    // initialise a global variable with inital value of 0
    let currentPrice = 0;
    
    // Stuff above the code like cron and general discord client.on
    
    console.log(price, 'PRICE UPDATED!');
    if (price !== currentPrice) {
        console.log(`Price changed from ${currentPrice} to ${price}`);
        currentPrice = price;
    }
    else {
        console.log(`Price remains at ${currentPrice}`);
    }
    

    第一次运行显然会将价格从 0 更改为第一个初始价格,但这没关系。

    【讨论】:

    • 谢谢!我正在尝试使用全局变量进行声明,这要好得多......我觉得很愚蠢,以至于我花了好几次之后也没有想出这个......甚至还不够接近。
    【解决方案2】:

    好吧,那么你有没有尝试过 previous_price = current_price 在将 previous_price 设置为当前某个价格后,运行它,然后在 console.log 之后,如果它不同或其他什么,那么它被设置为当前价格,然后它会改变在每个内部之后?

    这应该可行。

    【讨论】:

    • 不,不幸的是它是一样的......它仍然记录价格是定义的,而不是更改/相同的。我想有办法我不知道如何做到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多