← 中文资源

简体中文版本

in 检查键而非值

in 检查的是键是否存在,与值无关:值为 undefined 也算有,稀疏数组的空洞不算有;它还会沿原型链查找,Object.hasOwn 则只看自身属性。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

true
true
false
true false true
true
true
false
true

运行说明

in 检查键是否存在,与值的真假无关:值为 0 的 retries 打印 true、值为 undefined 的 label 打印 true,只有真正缺失的 timeout 打印 false。稀疏数组的下标 1 是空洞——1 in sparse 打印 false,尽管读它也得到 undefined。

原型成员也能查到:toString in settings 沿链为 true,Object.hasOwn(settings, “toString”) 只看自身属性为 false。length in sparse 为 true——length 是数组自有属性。

要点提示

  • 空洞与 undefined 读起来一样,只有 in 能区分。
  • hasOwn 是严格检查;in 是沿链检查。

核心语句

console.log(0 in sparse, 1 in sparse, 2 in sparse);

代码示例

// `in` asks "does this key exist?", never "is this value non-null?"
const settings = { retries: 0, label: undefined };
console.log('retries' in settings);  // true - the key exists with value 0
console.log('label' in settings);    // true - present even though the value is undefined
console.log('timeout' in settings);  // false - really missing

// On arrays the keys are indices: holes are false, defined slots are true
const sparse = ['a', , 'c'];         // index 1 is a hole
console.log(0 in sparse, 1 in sparse, 2 in sparse); // true false true
console.log(sparse[1] === undefined); // reading the hole also yields undefined

// `in` walks the prototype chain; Object.hasOwn stops at own properties
console.log('toString' in settings);              // true - inherited
console.log(Object.hasOwn(settings, 'toString')); // false - not an own property
console.log('length' in sparse);                  // true - length is an array property