javascript オブジェクトを比較演算子で比較した結果

javascript オブジェクトを比較演算子で比較した結果

javascriptで、オブジェクトを比較演算子で比較した結果を記述してます。

環境

  • OS windows11 pro 64bit
  • ブラウザ chrome 104.0.5112.101

比較演算子で比較

オブジェクトは、比較演算子で比較した場合、変わった結果になるので、注意が必要です。

console.log( {"a":1} ==  {"a":1} ) // false
console.log( {"a":1} === {"a":1} ) // false
console.log( {"a":1} <   {"a":1} ) // false
console.log( {"a":1} >   {"a":1} ) // false
console.log( {"a":1} <=  {"a":1} ) // true
console.log( {"a":1} >=  {"a":1} ) // true

正しく比較する場合は「JSON.stringify」を使用します。

console.log( JSON.stringify({"a":1}) ==  JSON.stringify({"a":1}) ) // true
console.log( JSON.stringify({"a":1}) === JSON.stringify({"a":1}) ) // true
console.log( JSON.stringify({"a":1}) <   JSON.stringify({"a":1}) ) // false
console.log( JSON.stringify({"a":1}) >   JSON.stringify({"a":1}) ) // false
console.log( JSON.stringify({"a":1}) <=  JSON.stringify({"a":1}) ) // true
console.log( JSON.stringify({"a":1}) >=  JSON.stringify({"a":1}) ) // true