简体   繁体   English

为什么这两个日期在javascript中不相等?

[英]Why these two dates are not equal in javascript?

I'm comparing two dates in objA and objB, and they are not equal as the following console output shows. 我正在比较objA和objB中的两个日期,它们不相等,如以下控制台输出所示。
Can't understand why.. 不明白为什么。

objA[keysA[i]]
Sun Sep 25 2016 00:00:00 GMT+0900 (KST)
objB[keysA[i]]
Sun Sep 25 2016 00:00:00 GMT+0900 (KST)
typeof objA[keysA[i]]
"object"
typeof objB[keysA[i]]
"object"
objA[keysA[i]] !== objB[keysA[i]]
true

You'll need to stringify the dates & compare them that way. 您需要对日期进行分类并以这种方式进行比较。 For example: 例如:

var date1 = new Date(); 
var date2 = new Date();

console.log (date1==date2); // This will print false

But if we stringify the dates and compare them that way this will become true, like so: 但是,如果我们对日期进行字符串化并以这种方式进行比较,那么这将成为事实,就像这样:

console.log (date1.toString() === date2.toString())

In JavaScript you compare objects by reference. 在JavaScript中,您通过引用比较对象。

let a = {};
let b = {};
let c = a;

a == b //false
a == c //true

A simple way of comparing objects is to convert them to a string and compare the string. 比较对象的一种简单方法是将它们转换为字符串并比较该字符串。 You can use Date.prototype.toString to compare Date objects like this 您可以使用Date.prototype.toString这样比较Date对象

objA[keysA[i]].toString() !== objB[keysA[i]]].toString() //false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM