我试图在Node.js控制台中花一些时间使用JavaScript更新,在我的函数indexActiveTime中,我收集了小时,分钟和秒,并将它们输入到console.log中,假设将它们输出为当前系统时间,格式为00:00:00;我在最后调用该函数并运行node.js程序,由于某种原因,我仅获得以下输出。
undefined:undefined:undefined
undefined:undefined:undefined
undefined:undefined:undefined
我试图将其放入某些变量,不同的concat方法中,而我收到的唯一结果就是将其作为变量输出,就像这样。
${callActiveHours}:${callActiveMinutes}:${callActiveSeconds}
或
function getHours() { [native code] }:function getMinutes() { [native code] }:function getSeconds() { [native code] }
function addZero(i) {
if (i < 10) {
i = "0" + 1;
return i;
}
}
function indexActiveTime() {
var getIndexTime = new Date();
var callActiveHours = addZero(getIndexTime.getHours);
var callActiveMinutes = addZero(getIndexTime.getMinutes);
var callActiveSeconds = addZero(getIndexTime.getSeconds);
console.log(callActiveHours + ":" + callActiveMinutes + ":" + callActiveSeconds);
var activeTimeOut = setTimeout(indexActiveTime, 500);
}
indexActiveTime();
答案 0 :(得分:0)
如评论所示:
i < 10
为假时, addZero 函数返回 undefined i = '0' + 1
应该是i = '0' + i
function addZero(i) {
if (i < 10) {
// Fix assignment
i = "0" + i;
return i;
// Return i if condition is false
} else {
return i;
}
}
function indexActiveTime() {
var getIndexTime = new Date();
// Call methods, not just reference them
var callActiveHours = addZero(getIndexTime.getHours());
var callActiveMinutes = addZero(getIndexTime.getMinutes());
var callActiveSeconds = addZero(getIndexTime.getSeconds());
console.log(callActiveHours + ":" + callActiveMinutes + ":" + callActiveSeconds);
var activeTimeOut = setTimeout(indexActiveTime, 500);
}
indexActiveTime();
有关如何创建在所需时间间隔合理可靠运行的计时器的信息,请参见this答案。