紀錄工作經驗、相關知識,解決技術相關問題。

Javascript

JS in operator:檢查屬性是否存在於物件或原型鏈

JS in operator:檢查屬性是否存在於物件或原型鏈 特色圖片

JS in operator(in 運算子)用來檢查指定的屬性,是否存在於物件本身或它的原型鏈上,存在回傳 true,否則回傳 false。

const car = { make: "Honda", model: "Accord", year: 1998 };

console.log("make" in car);    // true
console.log("color" in car);   // false

delete car.make;
if ("make" in car === false) {
  car.make = "Suzuki";
}

console.log(car.make);         // "Suzuki"

in 只能檢查「屬性名稱」,不能拿來找值。要找陣列裡有沒有某個值,請用 Array.prototype.includes();Set 則用 Set.prototype.has()。

語法

prop in object
#prop in object

依 MDN 說明:

  • prop:優先順序在 9(關係運算子)以上的運算式,值會被轉成屬性鍵(字串或 Symbol)。
  • #prop:在外層 class 宣告過的私有元素識別字(詳見後面「私有欄位檢查」)。
  • object:優先順序在 10(位元位移)以上的運算式,必須是要檢查的物件。

回傳值是布林值,表示 object 本身或原型鏈上有沒有這個屬性。#prop in object 則是檢查 object 自己有沒有這個私有元素。

基本用法:物件、陣列與內建物件

// 陣列
const trees = ["redwood", "bay", "cedar", "oak", "maple"];
console.log(0 in trees);              // true
console.log(3 in trees);              // true
console.log(6 in trees);              // false
console.log("bay" in trees);          // false(要寫索引,不是值)
console.log("length" in trees);       // true(length 是 Array 的屬性)
console.log(Symbol.iterator in trees);// true

// 內建物件
console.log("PI" in Math);            // true

// 自訂物件
const myCar = { make: "Honda", model: "Accord", year: 1998 };
console.log("make" in myCar);         // true
console.log("model" in myCar);        // true

陣列用 in 檢查的是索引,不是元素的值,所以 "bay" in trees 是 false。要檢查值是否存在,請用 includes()。

右邊必須是物件

右邊不能是原始值。用 String 建構函式建立的字串物件可以,字串字面值(原始值)會丟出 TypeError:

const color1 = new String("green");
console.log("length" in color1);   // true

try {
  "length" in "coral";
} catch (e) {
  console.log(e.name);             // "TypeError"
}

delete、undefined 與陣列空位

屬性被 delete 刪掉之後,in 回傳 false:

const myCar = { make: "Honda", model: "Accord", year: 1998 };
delete myCar.make;
console.log("make" in myCar);   // false

const trees = ["redwood", "bay", "cedar", "oak", "maple"];
delete trees[3];
console.log(3 in trees);        // false

屬性值設成 undefined 但沒有刪除,in 仍然回傳 true:

const car = { make: "Honda" };
car.make = undefined;

console.log("make" in car);          // true
console.log(car.make !== undefined); // false

MDN 指出,屬性可以存在但值是 undefined,所以 "x" in obj 和 obj.x !== undefined 不是同一件事。要讓 in 回傳 false,要用 delete 刪除屬性,而不是把值設成 undefined。

陣列的空位(empty slot)也不算有這個索引,即使直接讀取得到的是 undefined:

const empties = new Array(3);
console.log(empties[2]);     // undefined
console.log(2 in empties);   // false

const filled = new Array(3).fill(undefined);
console.log(2 in filled);    // true

用 fill() 填入值之後,索引就存在了。

原型鏈:in 會連繼承的屬性一起算

in 會往原型鏈上找,所以繼承來的屬性也會回傳 true。把物件當成任意鍵值對來儲存時,這可能不是你要的結果:

const ages = { alice: 18, bob: 27 };

function hasPerson(name) {
  return name in ages;
}

console.log(hasPerson("alice"));          // true
console.log(hasPerson("carol"));          // false
console.log(hasPerson("hasOwnProperty")); // true

"hasOwnProperty" 是從 Object.prototype 繼承來的,所以也被算進去。

MDN 的建議是只想檢查物件自己的屬性時,改用 Object.hasOwn():

const ages = { alice: 18, bob: 27 };

function hasPerson(name) {
  return Object.hasOwn(ages, name);
}

console.log(hasPerson("alice"));          // true
console.log(hasPerson("hasOwnProperty")); // false

MDN 也建議,如果是拿物件當鍵值對儲存,可以考慮改用原型為 null 的物件或 Map,避免其他類似的問題:

const ages = new Map([
  ["alice", 18],
  ["bob", 27],
]);

function hasPerson(name) {
  return ages.has(name);
}

console.log(hasPerson("alice"));          // true
console.log(hasPerson("hasOwnProperty")); // false

in 與 Object.hasOwn()、Object.prototype.hasOwnProperty() 的差別,在於前者包含原型鏈,後兩者只看物件自己的屬性。Object.hasOwn() 與 hasOwnProperty() 各自的用法,請參考它們的語法文。

in 與 for…in 的差別

兩者都會處理原型鏈上的屬性,但用途不同:

比較項目in 運算子for…in 迴圈
用途檢查單一屬性存不存在走訪物件的屬性
回傳布林值無(每次迴圈取得一個屬性名稱)
不可列舉的屬性也會算(只要存在)不會走訪
Symbol 屬性可以檢查不會走訪

依 MDN 說明,for...in 只走訪可列舉的字串屬性(包含繼承來的可列舉屬性),忽略以 Symbol 為鍵的屬性。

const child = Object.create({ inherited: 1 });
child.own = 2;

const keys = [];
for (const k in child) keys.push(k);

console.log(keys.join(","));              // "own,inherited"
console.log("inherited" in child);        // true
console.log(Object.hasOwn(child, "inherited")); // false

for...in 的完整用法請參考 for…in 的語法文。

私有欄位檢查:#x in obj

in 也可以檢查物件有沒有某個私有欄位或私有方法,寫法是左邊放不加引號的私有識別字。MDN 稱它為 branded check,因為只有用該 class 建構出來的物件才會回傳 true,之後就可以安全地存取其他私有元素。

class C {
  #x;
  static isC(obj) {
    return #x in obj;
  }
}

console.log(C.isC(new C()));   // true
console.log(C.isC({}));        // false

存取沒有宣告該私有元素的物件,會丟出 TypeError 而不是回傳 undefined,所以沒有這個語法時,要靠 try...catch 判斷。

class Person {
  #age;
  constructor(age) {
    this.#age = age;
  }
  static isPerson(o) {
    return #age in o;
  }
  ageDifference(other) {
    return this.#age - other.#age;
  }
}

const p1 = new Person(20);
const p2 = new Person(30);

console.log(p1.ageDifference(p2));   // -10
console.log(Person.isPerson(p1));    // true
console.log(Person.isPerson({}));    // false

try {
  p1.ageDifference({});
} catch (e) {
  console.log(e.name);               // "TypeError"
}

補充說明:#x in obj 要求私有元素必須先在外層 class 宣告,否則會丟出 SyntaxError。這個檢查也可以寫成 class 的 Symbol.hasInstance 方法,讓 instanceof 做同樣的判斷,請參考 instanceof 的語法文。

注意事項

  1. 只檢查屬性名稱:要找值請用 includes()(陣列)或 has()(Set、Map)。
  2. 右邊不能是原始值:否則丟出 TypeError。
  3. 會連原型鏈一起找:只要物件自己的屬性,請改用 Object.hasOwn()。
  4. undefined 不等於不存在:屬性值設成 undefined 仍然是 true,要用 delete 才會變 false。
  5. 陣列空位算不存在:new Array(3) 的索引 2 in 結果是 false。
  6. 陣列要寫索引:"bay" in trees 檢查的是名稱為 "bay" 的屬性。

支援版本

依 MDN 瀏覽器相容性資料(browser-compat-data 8.1.10,查詢日期 2026-11-24):in 從 Chrome 1、Edge 12、Firefox 1、Safari 1 開始支援,Node.js 從 0.10.0 開始,Deno 從 1.0 開始,Internet Explorer 從 5.5 開始。

補充說明:範例在 Node.js 執行。MDN 的範例是陣列與內建物件、字串物件、delete 與 undefined、陣列空位、原型鏈與 Object.hasOwn()、Map 與私有欄位;for...in 的對照範例是依 MDN 的說明另外示範的。

參考資料與延伸閱讀

發佈留言