如何在 JavaScript 中檢查物件是否有某個屬性
在 JavaScript 中,我們經常需要檢查物件是否有某個屬性,以便進行相應的操作。有幾種方法可以實現這個功能,下面介紹其中幾種常用的方法:
TL;DR
方法 | 是否能檢查原型鏈上的屬性 | 說明 |
---|---|---|
in 運算子 | ✅ | 檢查物件自身及其原型鏈上的屬性,若存在則回傳 true ,否則回傳 false 。 |
Reflect.has() | ✅ | 檢查物件自身及其原型鏈上的屬性,行為類似於 in 運算子。 |
Object.prototype.hasOwnProperty() | ❌ | 僅檢查物件自身的屬性,若存在則回傳 true ,否則回傳 false 。 |
Object.hasOwn() | ❌ | 類似於 hasOwnProperty ,但語法更簡潔,僅檢查物件自身的屬性。 |
in 運算子
in
運算子是 JavaScript 中用來檢查物件是否有指定屬性的方法之一。這個運算子會檢查物件自身及其原型鏈上是否有指定的屬性,如果有則回傳 true
,否則回傳 false
。
const parent = {
type: "Person",
};
const city = Symbol("city");
const child = Object.create(parent);
child.name = "Kevin";
child.age = 30;
child[city] = "Taipei";
console.log("name" in child); // true
console.log("type" in child); // true
console.log(city in child); // true
Reflect.has()
方法
Reflect.has()
方法是 JavaScript 中用來檢查物件是否有指定屬性的方法之一。這個方法和 in
運算子類似,會檢查物件自身及其原型鏈上是否有指定的屬性。
const parent = {
type: "Person",
};
const city = Symbol("city");
const child = Object.create(parent);
child.name = "Kevin";
child.age = 30;
child[city] = "Taipei";
console.log(Reflect.has(child, "name")); // true
console.log(Reflect.has(child, "type")); // true
console.log(Reflect.has(child, city)); // true
Object.prototype.hasOwnProperty() 和 Object.hasOwn()
Object.prototype.hasOwnProperty()
是 JavaScript 中用來檢查物件是否有指定屬性的方法之一。這個方法會檢查物件自身是否有指定的屬性,如果有則回傳 true
,否則回傳 false
。需要注意的是,Object.prototype.hasOwnProperty()
方法不會檢查原型鏈上的屬性。
如果你想要更簡潔的方式來檢查物件是否有指定屬性,可以使用 Object.hasOwn()
const parent = {
type: "Person",
};
const city = Symbol("city");
const child = Object.create(parent);
child.name = "Kevin";
child.age = 30;
child[city] = "Taipei";
console.log(Object.prototype.hasOwnProperty.call(child, "name")); // true
console.log(Object.prototype.hasOwnProperty.call(child, "type")); // false
console.log(Object.prototype.hasOwnProperty.call(child, city)); // true
console.log(Object.hasOwn(child, "name")); // true
console.log(Object.hasOwn(child, "type")); // false
console.log(Object.hasOwn(child, city)); // true