Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ความเท่าเทียมของ Objects ใน JavaScript (Reference vs Value)

ใน JavaScript Primitive Types (string, number, boolean, null, undefined, symbol, bigint) เปรียบเทียบด้วย Value แต่ Objects (Object, Array, Function) เปรียบเทียบด้วย Reference (Memory Address)

ตัวอย่างโค้ด

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Object Equality</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 18px; font-weight: 500; color: rebeccapurple; }
  </style>
</head>
<body>
  <h1>Equality of Objects ใน JavaScript</h1>
  <div class="result"></div>
  <button class="Btn">คลิกที่นี่</button>
  <h3>คลิกปุ่มด้านบนเพื่อเปรียบเทียบ Objects</h3>
  <script>
    const BtnEle = document.querySelector(".Btn");
    const resEle = document.querySelector(".result");
    
    const obj = { name: "Rohan", age: 21 };
    const obj1 = { name: "Rohan", age: 21 }; // Object ใหม่ ค่าเหมือนกัน
    const obj2 = obj; // Reference เดียวกับ obj
    
    BtnEle.addEventListener("click", () => {
      if (obj !== obj1) {
        resEle.innerHTML = "obj ไม่เท่ากับ obj1 (Reference ต่างกัน)<br>";
      }
      if (obj2 === obj) {
        resEle.innerHTML += "obj2 เท่ากับ obj (Reference เดียวกัน)";
      }
    });
  </script>
</body>
</html>

การเปรียบเทียบ Object แบบ Deep Equality

const a = { x: 1, y: { z: 2 } };
const b = { x: 1, y: { z: 2 } };

// 1. JSON.stringify (Simple แต่มีข้อจำกัด)
JSON.stringify(a) === JSON.stringify(b); // true
// ❌ ไม่รองรับ: Function, Symbol, undefined, Circular Ref, Key Order

// 2. Lodash isEqual (แนะนำสำหรับ Production)
_.isEqual(a, b); // true

// 3. Custom Deep Equal
function deepEqual(a, b) {
  if (a === b) return true;
  if (a == null || b == null || typeof a !== 'object' || typeof b !== 'object') return false;
  
  const keysA = Object.keys(a), keysB = Object.keys(b);
  if (keysA.length !== keysB.length) return false;
  
  return keysA.every(key => deepEqual(a[key], b[key]));
}

// 4. Object.keys + every (Shallow)
Object.keys(a).length === Object.keys(b).length &&
Object.keys(a).every(key => a[key] === b[key]);

ตารางสรุป Equality

ประเภทตัวอย่าง== / ===หมายเหตุ
Primitive1 === 1, "a" === "a"Value Comparisonเท่ากันถ้าค่าเท่ากัน
Object (Same Ref)obj === objtrueReference เดียวกัน
Object (Diff Ref){} === {}falseReference ต่างกัน
Array[1] === [1]falseReference ต่างกัน
Functionf === ftrue/falseขึ้นอยู่กับ Reference

ผลลัพธ์

obj ไม่เท่ากับ obj1 (Reference ต่างกัน), obj2 เท่ากับ obj (Reference เดียวกัน)