【发布时间】:2015-02-11 14:10:30
【问题描述】:
代码如下:
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,因为它是数组collection 中的第二个值。但事实证明是-1。
这是为什么呢? JavaScript Date 类型有什么特别需要注意的地方吗?
这是一个sn-p:
(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>
【问题讨论】:
-
d是 Date 的一个新实例,即使日期与索引 1 相同,但对象不同,因此结果为 -1。 -
两个不同的实例永远不会相等。仅供参考,ES6 通过引入
Array#findIndex解决了这个问题,它接受一个回调进行比较:collection.findIndex(function(x) { return x.valueOf() === d.valueOf(); });。
标签: javascript date indexof