How to correctly use JavaScript indexOf in a date array

前端 未结 5 1093
你的背包
你的背包 2021-02-12 13:07

Here is the code:

var collection = [new Date(2014, 11, 25), new Date(2014, 11, 24)];
var d=new Date(2014, 11, 24);

var idx= collection.indexOf(d);
5条回答
  •  迷失自我
    2021-02-12 13:16

    Two different objects are never equal to each other, even if they have the same properties / values. Here is a forward looking answer to the problem:

    ECMAScript 6 introduces Array#findIndex which accepts a comparison callback:

    var index = collection.findIndex(function(x) { 
        return x.valueOf() === d.valueOf(); 
    });
    

    Browser support isn't great yet though.

提交回复
热议问题