I've got a selection of times, but I want to keep the leading zero:
var fastTrainReading = [0943, 0957, 1006, 1013 , 1027, 1036, 1043, 1057, 1106, 1113, 1127, 1136, 1213, 1227, 1236, 1243, 1257, 1306, 1313, 1327, 1336, 1343, 1357, 1406, 1413, 1427, 1436, 1443, 1457, 1506, 1513, 1527, 1537, 1543, 1559, 1606, 1613, 1627, 1636, 1643, 1657, 1704, 1718, 1728, 1735, 1749, 1758, 1816, 1830, 1847, 1859, 1906, 1911, 1930, 1936, 1941, 1959, 2006, 2017, 2027];
This is the math perf开发者_JS百科ormed:
var currentTime = hour*100 + mins;
if ((day == 0) || (day == 6)) {
document.write ("There are no buses today");
} else {
var displayCount = 0;
var TrainStr1 = "";
for (var i=0, len=fastTrainReading.length; i<len; ++i) {
if ((fastTrainReading[i] > currentTime) && (displayCount < 2)) {
displayCount = displayCount+1;
TrainStr1=TrainStr1 + fastTrainReading[i] + "<br/>";
}
}
}
document.write (TrainStr1)
I had a pretty good search through, if I missed something feel free to abuse me (but point me in the right direction).
Simplest solution is to store your time data as strings e.g. var fastTrainReading = ['0943', ...
. JavaScript will cast to integer for you in your calculation routines.
For a comprehensive string formatting solution that adheres to conventional principles, try sprintf() for javascript: http://www.diveintojavascript.com/projects/javascript-sprintf
You can try to use .toString()
like: TrainStr1=TrainStr1 +
fastTrainReading[i].toString()
+ "<br/>";
alt to save your times as strings.
By default you won't get the leading zeroes.
As you know the length of TrainStr1 is 4, you can use the following function to get zeroes.
function formatted(time) {
var s = "0000" + time;
return s.substr(s.length-4); }
You can call the function 'formatted' before using document.write
You need to zero pad your numbers.
Number.prototype.zf = function _zeroFormat(digits)
{
var n = this.toString(), pLen = digits - n.length;
for ( var i = 0; i < pLen; i++)
{
n = '0' + n;
}
return n;
}
if ((fastTrainReading[i] > currentTime.zf(4)) && (displayCount < 2)) {
displayCount = displayCount+1;
TrainStr1=TrainStr1 + fastTrainReading[i] + "<br/>";
}
Once you've normalized all of your numbers to be 0-padded to 4 digits, string comparison is possible. Otherwise, you'll have issues. As things stand, it looks like your code was trying to compare a string (like an element from fastTrainReading) and a number (currentTime).
Just declare your array as strings:
var fastTrainReading = ['0943', '0957', '1006', '1013'];
And don't worry fastTrainReading[i] > currentTime
will still work.
'100' > 99 == true
精彩评论