【发布时间】:2015-08-10 13:35:56
【问题描述】:
我正在尝试理解 JavaScript 世界中的类型。我的页面正在使用moment.js。我有一个函数,有时会返回 moment(),有时会返回 string(它是旧代码变得疯狂)。
我的代码如下所示:
var now = getDate();
if (now instanceof moment) {
console.log('we have a moment.');
} else {
console.log('we have a string.');
}
function getDate() {
var result = null;
// Sometimes result will be a moment(), other times, result will be a string.
result = moment();
return result;
}
当我执行上面的代码时,我从来没有得到we have a moment.。即使我手动设置result = moment();。这是为什么?我是误会instanceof 还是moment?
【问题讨论】:
-
尝试打印“type of moment()”以确保您期待正确的值。
-
尝试使用 typeof,并调试:console.log(typeof now);
-
应该使用
typeof now === "string"
标签: javascript momentjs