使用比较运算符或 JSON.stringlify() 在 JavaScript 中进行对象比较的复杂性?

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/6 6:36:17

假设以下是我们的对象 −

var object1 = { firstName: "David" };
var object2 = { firstName: "David" };

使用比较运算符(== 或 ===)不会得到正确的结果。为此使用 JSON.stringify()。

示例

以下是实现这两种方式并显示正确结果的代码 −

var object1 = { firstName: "David" };
var object2 = { firstName: "David" };
if (object1 == object2)
   console.log("using == operator result ==> true");
else
   console.log("using == operator result ==> false");
if (JSON.stringify(object1) == JSON.stringify(object2))
   console.log("using JSON.stringify() operator result ==> true");
else
   console.log("using JSON.stringify() operator result ==> false");

要运行上述程序,您需要使用以下命令 −

node fileName.js.

这里,文件名是 demo224.js。

输出

输出如下 −

PS C:\Users\Amit\JavaScript-code> node demo224.js
using == operator result ==> false
using JSON.stringify() operator result ==> true

相关文章


有用资源