繁体   English   中英

为什么日期/时间在 node.js 控制台中输出“未定义”?

[英]Why Date/Time outputting "undefined" in node.js console?

我试图花时间在 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();

正如评论所暗示的那样:

  1. 当条件i < 10为假时, addZero函数返回undefined
  2. 赋值i = '0' + 1应该是i = '0' + i
  3. 它被传递一个函数引用而不是调用函数的结果,所以它总是假的(并且总是返回undefined )。

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

有关如何创建以所需间隔合理可靠地运行的计时器,请参阅答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM