How to correctly use JavaScript indexOf in a date array

前端 未结 5 1037
你的背包
你的背包 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条回答
  •  旧时难觅i
    2021-02-12 13:23

    This is because your "d" object is the different object. In other words:

    var d = new Date(2014, 11, 24);
    
    d === new Date(2014, 11, 24); // returns false
    

    You can try this:

    var d = new Date(2014, 11, 24);
    var collection = [new Date(2014, 11, 25), d];
    
    var idx = collection.indexOf(d); // returns 1
    

提交回复
热议问题