这是代码:
var collection = [new Date(2014, 11, 25), new Date(2014, 11, 24)];
var d=new Date(2014, 11, 24);
var idx= collection.indexOf(d);
Run Code Online (Sandbox Code Playgroud)
我想变量idx应该有一个值,1因为它是数组中的第二个值collection.但事实证明是这样的-1.
这是为什么?Date我需要注意的JavaScript 类型有什么特别的东西吗?
这是一个片段:
(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);
});
})();Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
Pau*_* S. 46
除非你将它们序列化,否则两个对象将永远不会相等.幸运的是,Date很容易序列化为整数.
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
Run Code Online (Sandbox Code Playgroud)
两个不同的对象永远不会彼此相等,即使它们具有相同的属性/值.以下是该问题的前瞻性答案:
ECMAScript 6引入Array#findIndex了接受比较回调:
var index = collection.findIndex(function(x) {
return x.valueOf() === d.valueOf();
});
Run Code Online (Sandbox Code Playgroud)