IndexOf 不在 ie 中使用 date tolocalestring 但 ie 支持它

IndexOf not working with date tolocalestring in ie but ie supports it

所以我有一些代码可以在其他浏览器上运行,但在 IE 中不起作用。 我可以通过向浏览器记录输出来确认 indexOf 函数受支持并且可以正常工作,因为 console.log('array.indexOf(2) = ' + array.indexOf(2)); 代码在控制台中输出 0。

根据我的日志记录输出,其他值是正确的,一切看起来都应该工作,但 if 语句中的代码永远不会被命中。

这是我 javascript 登录到控制台的图像

我尝试了很多东西,我在代码中突出显示了这些东西,比如使用 .toString()jQuery.inArray 以及 daySetting[0].includes

console.log('daySetting[0] = ' + daySetting[0]);

console.log('new Date().toLocaleString("en-us", { weekday: "short" }) = ' + new Date().toLocaleString('en-us', { weekday: 'short' }));

console.log('daySetting[0].indexOf(new Date().toLocaleString("en-us", { weekday: "short" })) = ' + daySetting.indexOf(new Date().toLocaleString('en-us', { weekday: 'short' })));

var array = [2, 9, 9]; //test array
console.log('array.indexOf(2) = ' + array.indexOf(2));

if (daySetting[0].toString().indexOf(new Date().toLocaleString('en-us', { weekday: 'short' })) !== -1) {
  //|| daySetting[0].includes(new Date().toLocaleString('en-us', { weekday: 'short' }))//tried the includes method and .toString() method
  //if (jQuery.inArray(new Date().toLocaleString('en-us', { weekday: 'short' }), daySetting) != -1) {//tried jquery in array
  console.log("dayHours = " + dayHours); //expecting this to be output
  continue; //code is inside a loop
}

我希望看到代码 console.log("dayHours = " + dayHours); 被记录到控制台,但事实并非如此。 这在其他浏览器中工作正常,但我无法弄清楚发生了什么。

这里有一个fiddle的代码https://jsfiddle.net/q8pod2xj/1/

问题不在于 indexOf。

new Date().toLocaleString('en-us', { weekday: 'short' }) returns 'Thu' (length=4), 在 space第 0 个索引。使用 substr(1).

避免了它
var theHours = "Mon: Open 9am - 5:30pm, Tues: Open 9am - 5:30pm, Wed: Open 9am - 5:30pm, Thurs: Open 9am - 5:30pm, Fri: Open 9am - 5:30pm, Sat: Open 9am - 5pm, Sun: Open 11am - 5pm";
var days = theHours.split(',');
for (var i = 0; i < days.length; i++) {
    var daySetting = days[i].split(/:(.+)/);
    var dayHours = daySetting[1];

    if (daySetting[0].indexOf(new Date().toLocaleString('en-us', { weekday: 'short' }).substr(1)) !== -1) {
        console.log("dayHours = " + dayHours); //expecting this to be output
        continue; //code is inside a loop
    }
}