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

时间:2016-10-26 03:44:52

标签: javascript equality

我比较objA和objB中的两个日期,它们不相同,如下面的控制台输出所示。
无法理解为什么......

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

2 个答案:

答案 0 :(得分:1)

您需要将日期与字母串联起来。比较他们那样。例如:

{
    "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",    
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Configuration":"1.0.0",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Configuration.CommandLine": "1.0.0",
    "MailKit": "1.8.1"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "web.config", 
      "appsettings.json"
    ]
  },

  "tooling": {
    "defaultNamespace": "Company.Website"
  }
}

但是如果我们将日期字符串化并以这种方式进行比较,那么这将成为现实,如下:

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

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

答案 1 :(得分:1)

在JavaScript中,您可以通过引用比较对象。

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

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

比较对象的一种简单方法是将它们转换为字符串并比较字符串。您可以使用Date.prototype.toString来比较Date这样的对象

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