物件屬性操作是 JS 核心功夫。本文系統整理:刪除屬性 (delete)、檢測屬性存在性 (in/hasOwnProperty/propertyIsEnumerable)、枚舉屬性 (for...in/Object.keys)、原型鏈檢測 (isPrototypeOf/instanceof) 與類別判斷。
const person = { name: 'Tom', age: 25 };
delete person.age; // true
delete person['name']; // true
console.log(person); // {}
configurable: false) 無法刪除:Object.prototype、變數聲明 (var x)、函數聲明。TypeError;非嚴格模式靜默失敗回傳 false。const a = { p: { x: 1 } };
const b = a.p;
delete a.p;
console.log(a.p); // undefined
console.log(b.x); // 1 (b 仍引用原物件)
| 方法 | 語法 | 檢測範圍 | 可枚舉限制 | 備註 |
|---|---|---|---|---|
| in 運算子 | 'prop' in obj | 自有 + 繼承 | 否 | 左邊必須字串 |
| hasOwnProperty | obj.hasOwnProperty('prop') | 僅自有 | 否 | 最常用、可檢測不可枚舉自有屬性 |
| propertyIsEnumerable | obj.propertyIsEnumerable('prop') | 僅自有 | **是** | 自有且可枚舉才 true |
| !== undefined | obj.prop !== undefined | 自有 + 繼承 | 否 | 屬性值為 undefined 會誤判 |
const obj = { x: 1 };
console.log('x' in obj); // true
console.log('toString' in obj); // true (繼承)
console.log(obj.hasOwnProperty('x')); // true
console.log(obj.hasOwnProperty('toString'));// false
console.log(obj.propertyIsEnumerable('x'));// true
console.log(Object.prototype.propertyIsEnumerable('toString'));// false (內建不可枚舉)
const obj = { x: 1, y: 2 };
for (const p in obj) {
console.log(p); // 'x', 'y' (鍵名)
console.log(obj[p]); // 1, 2 (值) -- 必須用括號語法
}
| 方法 | 回傳 | 包含不可枚舉 | 包含 Symbol |
|---|---|---|---|
| Object.keys(obj) | 字串鍵陣列 | 否 | 否 |
| Object.getOwnPropertyNames(obj) | 字串鍵陣列 | **是** | 否 |
| Object.getOwnPropertySymbols(obj) | Symbol 鍵陣列 | **是** | **是** |
| Reflect.ownKeys(obj) | 所有鍵陣列 | **是** | **是** |
const proto = { x: 1 };
const child = Object.create(proto);
console.log(proto.isPrototypeOf(child)); // true
console.log(Object.prototype.isPrototypeOf(proto)); // true
console.log([] instanceof Array); // true
console.log([] instanceof Object); // true
console.log(new Date() instanceof Date); // true
// 原理:檢查建構函數 prototype 是否在實例原型鏈上
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call({}); // "[object Object]"
Object.prototype.toString.call(null); // "[object Null]" (ES5+)
// 通用類別提取函數
function typeOf(obj) {
return Object.prototype.toString.call(obj).slice(8, -1);
}
console.log(typeOf(/regex/)); // "RegExp"
const obj = {};
Object.defineProperty(obj, 'readOnly', {
value: 42,
writable: false, // 嚴格模式下修改拋錯
enumerable: true, // 可被 for...in/keys 發現
configurable: false // 無法 delete、無法再次 defineProperty
});
掌握「刪除只影響自有屬性」、「in 檢測含繼承」、「hasOwnProperty 只看自有」、「propertyIsEnumerable 更嚴格」、「for...in 枚舉可枚舉含繼承」、「Object.keys 只取自有可枚舉」、「instanceof 檢查建構函數原型鏈」、「Object.prototype.toString.call 取得精確類別」這幾條核心規則,即能自信處理所有物件屬性操作場景。