[英]I have a javascript function, and I can't tell what I've done wrong
This is a program to ping several hosts and track their 这是一个程序来ping几台主机并跟踪它们
Here is the offending function 这是令人反感的功能
function parseHistory(){
for(i = 0; i < hosts.length; i++){
var countTotal = 0;
var countSuccessful = 0;
var timeTotal = 0;
for(j = 0; j < history[hosts[i]].length; j++){
if(history[hosts[i]][j].success){
countTotal++;
countSuccessful++;
timeTotal += history[hosts[i]][j].time;
} else {
countTotal++;
}
}
var uptimePercent = Math.round(countSuccessful / countTotal * 10000) / 100 + '%';
var averageTime = Math.round(timeTotal / countSuccessful * 100) / 100;
console.log('--- ' + hosts[i] + ' has ' + uptimePercent + ' uptime with an average round-trip time of ' + averageTime + 'ms');
}
console.log('---');
}
Where hosts
is an array of strings, and history
is an object that stores several arrays of result objects. 其中
hosts
是一个字符串数组,而history
是一个存储多个结果对象数组的对象。
My main problem is with this for
loop, it seems to be doing the math wrong but I can't tell where. 我的主要问题是与此
for
循环,它似乎在做数学错误,但我不知道在哪里。
Here is the output my program produces after about 30 seconds 这是我的程序在大约30秒后产生的输出
--- google.com has 100% uptime with an average round-trip time of 33ms
--- yahoo.com has 100% uptime with an average round-trip time of 112ms
--- <redacted> has 0% uptime with an average round-trip time of NaNms
--- 127.0.0.1 has 100% uptime with an average round-trip time of 2ms
---
--- google.com has 100% uptime with an average round-trip time of 11.67ms
--- yahoo.com has 100% uptime with an average round-trip time of 38ms
--- <redacted> has 66.67% uptime with an average round-trip time of 1ms
--- 127.0.0.1 has 100% uptime with an average round-trip time of 1.33ms
---
--- google.com has 100% uptime with an average round-trip time of 7.6ms
--- yahoo.com has 100% uptime with an average round-trip time of 23.4ms
--- <redacted> has 80% uptime with an average round-trip time of 0.75ms
--- 127.0.0.1 has 100% uptime with an average round-trip time of 1.2ms
The average times seem to be decreasing after every ping, but for no reason. 每次ping之后,平均时间似乎正在减少,但没有任何原因。 It looks like a math error somewhere to me but I can't find it.
在我看来,这似乎是数学错误,但我找不到它。
Can you tell me where my error is? 你能告诉我我的错误在哪里吗?
Full source: http://pastebin.com/G0mfBTPe 全文: http : //pastebin.com/G0mfBTPe
From your pastebin, I noticed that you continuously are lengthening the history[host]
list: 从您的pastebin中,我注意到您一直在延长
history[host]
列表:
setInterval(ping, pingIntervalMs, host, function(result){
history[host].push(result);
historyChanged = true;
});
What does the "result" structure look like? “结果”结构是什么样的? Perhaps you are pushing objects that default to ".success" but have zero ".time".
也许您正在推送默认为“ .success”但“ .time”为零的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.