How to correctly use JavaScript indexOf in a date array

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

    indexOf() won't work here... It's been well explained in the previous answers...

    You'd be able to create your own lookup for the index. Here's a simple example comparing the dates using their .getTime() value...

    (function() {
    
      var collection = [new Date(2014, 11, 25), new Date(2014, 11, 24)];
      var d = new Date(2014, 11, 24);
    
      var idx1 = -1;
      collection.forEach(function(item, index){
        if(d.getTime() == item.getTime())
          idx1 = index;
      });
    
      var intArray = [1, 3, 4, 5];
      var idx2 = intArray.indexOf(4);
    
      $('#btnTry1').on('click', function() {
        $('#result1').val(idx1);
      });
    
      $('#btnTry2').on('click', function() {
        $('#result2').val(idx2);
      });
    })();
    
    Index:
    
    
    
    Index:

提交回复
热议问题