首页 > 解决方案 > 日期值不断返回 NaN

问题描述

我想在 Javascript 中有一个当前日期为 'YYYY-MM-DD' 格式的变量。但是当我执行我的代码并在 console.log 中检查它时。它只是说 NaN

var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
console.log("the date format here is ", + date);

console.log 显示类似“这里的日期格式是 NaN”的输出

谁能说这里有什么问题?

标签: javascriptdate

解决方案


它只是:

console.log('the date format here is ', date);

不需要'+'

如果您正在考虑使用加号运算符使用字符串连接+,则正确的语法是

console.log('the date format here is ' + date);

但是,当涉及到您面临的场景时,我个人更喜欢 ES6 的模板文字

console.log(`the date format here is ${date}`);

推荐阅读