所以我遇到了被转换为字符串的Javascript Date对象与IE11中的in
运算符之间的这种奇怪的交互。.toLocaleString()
返回日期的字符串在使用in
运算符检查键时不起作用,即使通过另一个具有完全相同文本的字符串也可以正常工作。
该交互在Chrome中正常工作,但在IE11中似乎失败。我在这里错过了什么,有没有办法解决这个问题?
let days = {
Monday: {},
Tuesday: {},
Wednesday: {},
Thursday: {},
Friday: {},
Saturday: {},
Sunday: {}
};
// The example date should be a Monday
let currentDate = new Date('2018/8/20');
let currentDay = currentDate.toLocaleString('en-us', {
weekday: 'long'
});
console.log(currentDay);
console.log(typeof currentDay);
console.log(currentDay in days);
console.log('Monday' in days);
感谢您的任何输入!
这基本上就是为什么你应该坚持使用ISO日期字符串(2018-01-01T00:00Z
(,而不是使用任意格式。
或者,自己解析格式并使用new Date()
构造函数的其他重载,如下所示:
const currentDate = new Date(2018, 7 /* months start at 0 */, 20 /* days do not */, 0, 0, 0)
日期解析不好,IE不好,在这种情况下,两个坏事不好。
错的不是in
。您的日期在 IE 中无效。