以下代码中的最后一个日志在 Firefox 中不起作用。为什么?
(function() {
String.prototype.toDate = function() {
return new Date(this);
};
console.log(Date.parse("2012-01-31"));
console.log(new Date("2012-01-31"));
console.log("2012-01-31".toDate());
})();
为了在浏览器中测试这一点,我将上面的代码片段放入一个文件中并使用了以下 HTML。
<!DOCTYPE html>
<body>
<script src="wtf.js"></script>
</body>
NodeJS(v0.4.12):
1327932000000
Mon, 30 Jan 2012 14:00:00 GMT
Mon, 30 Jan 2012 14:00:00 GMT
Chrome (17.0.963.79):
1327968000000
Tue Jan 31 2012 10:00:00 GMT+1000 (EST)
Tue Jan 31 2012 10:00:00 GMT+1000 (EST)
火狐 (10.0):
1327968000000
Date {Tue Jan 31 2012 10:00:00 GMT+1000 (EST)}
Date {Invalid Date}
最佳答案
Firefox 的 String.prototype 中的
this
似乎没有将字符串作为字符串引用。如果您添加到您的方法中:
String.prototype.toDate = function() {
return new Date(String(this));
};
一切正常。
关于javascript - 字符串上下文中的新日期在 Firefox 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9832192/