映屿

Nodejs环境下控制台拼接字符串输出有undefind

今天在Nodejs环境下搓小工具,控制台输出拼接字符串时,发现有undefind,代码如下:

const date = new Date();
const year = date.getFullYear();
const month = date.getMonth();
const day = date.getDate();
const hour = date.getHours();
const minute = date.getMinutes();
const second = date.getSeconds();
const logTime = `[${year}-${month}-${day} ${hour}:${minute}:${second}] `;

class GenerateLog {
  static log() {
    process.stdout.write(logTime);
  }
}

console.log(GenerateLog.log() + "log output on the console");

输出确是这样:

[2025-3-22 18:56:33] undefindlog output on the console

原因 :GenerateLog.log()方法没有返回值,所以输出undefind,解决方法如下:

// 让log方法返回logTime
class GenerateLog {
  static log() {
    return logTime; // 返回字符串
  }
}

console.log(GenerateLog.log() + "log output on the console");

关键总结: Javascript中,如果方法没有返回值,那么输出的就是undefind

扩展

为什么 console.log() 本身会返回 undefined? 在 REPL 环境(如 Node.js 命令行或浏览器控制台)中,每条语句的执行结果会被隐式打印。由于 console.log() 函数本身没有返回值(即返回 undefined),因此会显示 undefined。但在脚本执行时,这一行为不会发生,因为脚本模式不自动打印返回值


有想对我说的?发一封邮件吧

______ ____ _____ _____ _____ _________ _______ _ __ _ _ .' ___ ||_ \|_ _||_ _||_ _| | _ _ | |_ __ \ / |_ [ | / |_ / |_ / .' \_| | \ | | | | | | |_/ | | \_|.---. _ .--. _ .--. _ __ | |__) |_ .--. ,--. `| |-'.---. | |--. .---.`| |-'`| |-' | | ____ | |\ \| | | ' ' | | | / /__\\[ `/'`\][ `/'`\][ \ [ ] | ___/[ `/'`\]`'_\ : | | / /'`\] | .-. |/ /__\\| | | | \ `.___] |_| |_\ |_ \ \__/ / _| |_ | \__., | | | | \ '/ / _| |_ | | // | |,| |,| \__. | | | || \__.,| |, | |, `._____.'|_____|\____| `.__.' |_____| '.__.'[___] [___] [\_: / |_____| [___] \'-;__/\__/'.___.'[___]|__]'.__.'\__/ \__/ \__.' "A man is not dead while his name is still spoken."