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);
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
.
Why is that? Is there any special thing for the JavaScript Date
type I need to pay attention?
Here is a snippet:
(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
is a new instance of Date, and even though the date is the same as index 1, the objects are different, hence the result being -1. – SpringspringboardArray#findIndex
, which accepts a callback for comparison:collection.findIndex(function(x) { return x.valueOf() === d.valueOf(); });
. – Roofer