admin管理员组

文章数量:1352205

I'm doing a project/game in HTML/JavaScript with a console, and I'm putting in "ping" in it. But when I run this code I just get "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);
    };
}

I'm doing a project/game in HTML/JavaScript with a console, and I'm putting in "ping" in it. But when I run this code I just get "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);
    };
}
Share Improve this question edited Sep 20, 2014 at 16:43 Jozef Dúc 9632 gold badges18 silver badges29 bronze badges asked Sep 20, 2014 at 16:28 PadnezzPadnezz 891 gold badge2 silver badges10 bronze badges 3
  • 5 you should use parenthesis to wrap (new Date().getTime() - start) – King King Commented Sep 20, 2014 at 16:30
  • 2 Read about operator precedence and type conversion. Your problem can be solved with parentheses. – Viktor Bahtev Commented Sep 20, 2014 at 16:32
  • you can use + to join string and number, but you can not use -, so you should wrap parenthesis to your minus work – worldask Commented Sep 20, 2014 at 16:34
Add a ment  | 

3 Answers 3

Reset to default 5

The - is causing an implicit conversion of this string:

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

to NaN. The + and - in your line are evaluated from left to right, so when you get to the -, you are evaluating 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. NaN - anything is still NaN.

By wrapping the (new Date().getTime() - start) in parentheses, the numerical operation is pleted first, then you are adding together String + Number. This results in a conversion from number to string, so your console.log will work as you expect.

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);
   };
}

本文标签: javascriptGetting NaN when consolelog()Stack Overflow