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
3 Answers
Reset to default 5The -
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
版权声明:本文标题:javascript - Getting NaN when console.log() - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743904856a2559331.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论