How to correctly use JavaScript indexOf in a date array

前端 未结 5 1026
你的背包
你的背包 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:32

    Two Objects will never be equal unless you serialise them. Lucky, Date is pretty easy to serialise as an integer.

    var collection = [new Date(2014, 11, 25), new Date(2014, 11, 24)],
        d = new Date(2014, 11, 24),
        idx;
    
    idx = collection.map(Number).indexOf(+d); // 1
    //              ^^^^^^^^^^^^         ^ serialisation steps
    

提交回复
热议问题