使用findIndex并排除旧浏览器

时间:2017-12-01 20:27:06

标签: javascript arrays methods

我想使用findIndex方法并排除所有不支持此方法的浏览器 - 特别是老朋友,例如< = IE11。

我认为我可以通过if / else声明来解决问题:

var albums = [
    {
        title: "Hash-Bar Loops",
        artist: "Deepchord",
        releasedate: "2011-06-27",
        label: "Soma Records",
        playtime: "1:19:23"
    },
    {
        title: "Liumin",
        artist: "Deepchord",
        releasedate: "2010-01-01" /* first match of findIndex - 1 */,
        label: "Modern Love",
        playtime: "1:19:28"
    },
    {
        title: "Coldest Season",
        artist: "Deepchord",
        releasedate: "2007-01-01",
        label: "Modern Love",
        playtime: "1:19:43"
    },
    {
        title: "Sommer",
        artist: "Deepchord",
        releasedate: "2012-08-27",
        label: "Soma Records",
        playtime: "1:14:36"
    },
    {
        title: "Atmospherica Vol. 2",
        artist: "Deepchord",
        releasedate: "2016-02-05",
        label: "Soma Records",
        playtime: "0:25:14"
    }
];

function init() {
    "use strict";

    if (Array.findIndex in window) {
        var first = albums.findIndex(function(album, index, albums) {
            return new Date(album.releasedate).getMonth() + 1 === 1;
        });

        console.log(first); /* 1 */
    } else {
        console.log("Sorry - old browser");
    }
}

window.addEventListener("load", init, false);

但是,在IE11中,我收到一条错误消息,导致else-block中的语句停止执行:

  

该对象不支持属性或方法findIndex。

还尝试了try / catch,但得到了同样的信息。

如何让现代浏览器使用findIndex和旧浏览器来忽略脚本中的相应区域?

0 个答案:

没有答案