Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Kiểm tra key có tồn tại trong object JavaScript

Có 2 cách chính để kiểm tra thuộc tính trong object, khác nhau ở việc có kiểm tra thuộc tính kế thừa (inherited) hay không.

1. Toán tử 'in' — Kiểm tra cả thuộc tính riêng và kế thừa

'tenKey' in doiTuong; // true / false

Ví dụ

<script>
  const employee = { name: "Ranjan", age: 25 };
  document.write('name' in employee);     // true (thuộc tính riêng)
  document.write('<br>');
  document.write('salary' in employee);   // false
  document.write('<br>');
  document.write('toString' in employee); // true (kế thừa từ Object.prototype)
</script>

2. hasOwnProperty() — Chỉ kiểm tra thuộc tính riêng

doiTuong.hasOwnProperty('tenKey'); // true / false

Ví dụ

<script>
  const employee = { name: "Ranjan", age: 25 };
  document.write(employee.hasOwnProperty('name'));     // true
  document.write('<br>');
  document.write(employee.hasOwnProperty('salary'));   // false
  document.write('<br>');
  document.write(employee.hasOwnProperty('toString')); // false (kế thừa)
</script>

Cách hiện đại: Object.hasOwn() (ES2022)

An toàn hơn hasOwnProperty (tránh lỗi khi object bị ghi đè phương thức).

Object.hasOwn(employee, 'name'); // true
Object.hasOwn(employee, 'toString'); // false

So sánh nhanh

Phương phápKiểm tra own propertyKiểm tra inheritedAn toàn
inCóCóCó
hasOwnPropertyCóKhôngCó (trừ khi bị shadow)
Object.hasOwn()CóKhôngCao nhất

Khi nào dùng cái nào?

  • Cần biết key có tồn tại ở đâu (kể cả prototype) → in.
  • Chỉ quan tâm key do dev định nghĩa → Object.hasOwn() (ưu tiên) hoặc hasOwnProperty().