如何在日期数组中正确使用JavaScript indexOf [英] How to correctly use JavaScript indexOf in a date array

查看:89
本文介绍了如何在日期数组中正确使用JavaScript indexOf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是代码:

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

var idx= collection.indexOf(d);

我想变量 idx 应该有一个值 1 因为它是数组集合中的第二个值。但结果是 -1

I guess the variable idx should have a value of 1 since it is the second value in the array collection. But it turns out to be -1.

为什么?我需要注意的JavaScript Date 类型是否有任何特殊之处?

Why is that? Is there any special thing for the JavaScript Date type I need to pay attention?

这是一个片段:

(function() {

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

  var idx1 = collection.indexOf(d);

  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);
  });
})();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Index:
<input type="text" id="result1" value="">
<button id="btnTry1">Find index in a date array</button>
<br />Index:
<input type="text" id="result2" value="">
<button id="btnTry2">Find index in a regular array</button>

推荐答案

两个对象永远不会是平等的除非你序列化它们。幸运的是,日期非常容易序列化为整数。

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

这篇关于如何在日期数组中正确使用JavaScript indexOf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆