首页 > 解决方案 > new Date().getTime() 在 JavaScript 中显示 NaN

问题描述

我正在尝试将当前时间保存在时间戳键内的临时对象中new Date.getTime(),并将其推送到全局可访问变量内的数组中GLOBAL_VAR。但是在我制作临时变量并打印它的值之后,它显示时间戳是NaN我不知道为什么我不能在对象中得到它(console.log()结果如下所示)

此外, handleOrderMessage当收到 socket.io 事件时调用函数我不知道这是否会影响new Date.getTime()函数,显示输出:

console.log("TEMP OBJECT IS", tempObject)
/*
{
id: "-909e-11ea-9ede-066a42ffe1ae",
​price: "0.1",
​quantity: "0.1",
​side: "buy",
​timestamp: NaN
}
*/
    function handleOrderMessage(msg) {


        let d = new Date();
        console.log(d.getTime());
        if (msg['status'] === "PLACED") {
            //for buy
            if (msg['orderSide'] === "Buy") {
                let tempObject = {
                    side: "buy",
                    id: msg["OrderID"],
                    timestamp: d.getTime(),
                    quantity: parseFloat(msg["Quantity"].toFixed(4)).toString(),
                    price: parseFloat(msg["Price"].toFixed(4)).toString()
                }
                //pushing to the global orders with price from msg as key
                if (tempObject.price in GLOBAL_VAR.bidOrdersPricesAsKey) {
                    GLOBAL_VAR.bidOrdersPricesAsKey[tempObject.price].push(tempObject);
                } else {
                    GLOBAL_VAR.bidOrdersPricesAsKey[tempObject.price] = [tempObject]
                }
                console.log("GLOBAL VAR BUY ORDERS PRICES ASK KEY", GLOBAL_VAR.bidOrdersPricesAsKey)
                console.log("TEMP OBJECT IS", tempObject)
      }
    }

标签: javascripthtmlnangettime

解决方案


以下似乎工作正常,不知道为什么你会得到 NaN。请提供完整的工作代码来解决问题。

doit();
function doit() {
  let d = new Date();
  let tempObject = {
    side: "buy",
    timestamp: d.getTime()
  };
  console.log(tempObject);
}

推荐阅读