简体   繁体   English

当console.log()时获得NaN

[英]Getting NaN when console.log()

I'm doing a project/game in HTML/JavaScript with a console, and I'm putting in "ping" in it. 我正在使用控制台在HTML / JavaScript中进行项目/游戏,并在其中执行“ ping”操作。 But when I run this code I just get "NaN". 但是,当我运行此代码时,我只会得到“ NaN”。

function ping(IP){
    for (var i = 0; i <= 3; i++) {
        var start = new Date().getTime();
        console.log("64 bytes from " + IP + ": icmp_seq=" + i + " ttl=64 time: " + new Date().getTime() - start);
    };
}

The - is causing an implicit conversion of this string: -导致此字符串的隐式转换:

"64 bytes from " + IP + ": icmp_seq=" + i + " ttl=64 time: " + new Date().getTime()

to NaN . NaN The + and - in your line are evaluated from left to right, so when you get to the - , you are evaluating String - Number . 行中的+-是从左到右评估的,因此,到达- ,您是在评估String - Number In JS, this causes the string to be converted to a number (or NaN if it cannot be converted), which is obviously not what you want. 在JS中,这会使字符串转换为数字(如果无法转换,则为NaN ),这显然不是您想要的。 NaN - anything is still NaN . NaN - anything仍然是NaN

By wrapping the (new Date().getTime() - start) in parentheses, the numerical operation is completed first, then you are adding together String + Number . 通过将(new Date().getTime() - start)括在括号中,首先完成数字运算,然后将String + Number加在一起。 This results in a conversion from number to string, so your console.log will work as you expect. 这将导致从数字到字符串的转换,因此console.log将按预期工作。

You can't directly use concatenation and math... 您不能直接使用串联和数学运算...

" ttl=64 time: " + new Date().getTime() - start);

So add the code in parenthesis as follows... 因此,将代码添加到括号中,如下所示...

console.log("64 bytes from " + IP + ": icmp_seq=" + i + " ttl=64 time: " + (new Date().getTime() - start));
function ping(IP){
   for (var i = 0; i <= 3; i++) {
       var start = new Date().getTime();
       var newTime = new Date().getTime() - start;
       console.log("64 bytes from " + IP + ": icmp_seq=" + i + " ttl=64 time: " + newTime);
   };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM