Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. JavaScript
  3. JavaScript 参考
  4. 表达式和运算符
  5. in

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

in

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2015年7月⁩.

如果指定的属性在指定的对象或其原型链中,则in运算符返回true

尝试一下

const car = { make: "Honda", model: "Accord", year: 1998 };console.log("make" in car);// Expected output: truedelete car.make;if ("make" in car === false) {  car.make = "Suzuki";}console.log(car.make);// Expected output: "Suzuki"

语法

prop in object

参数

prop

一个字符串类型或者 symbol 类型的属性名或者数组索引(非 symbol 类型将会强制转为字符串)。

objectName

检查它(或其原型链)是否包含具有指定名称的属性的对象。

描述

下面的例子演示了一些in 运算符的用法。

js
// 数组var trees = new Array("redwood", "bay", "cedar", "oak", "maple");0 in trees; // 返回 true3 in trees; // 返回 true6 in trees; // 返回 false"bay" in trees; // 返回 false (必须使用索引号,而不是数组元素的值)"length" in trees; // 返回 true (length 是一个数组属性)Symbol.iterator in trees; // 返回 true (数组可迭代,只在 ES2015+ 上有效)// 内置对象"PI" in Math; // 返回 true// 自定义对象var mycar = { make: "Honda", model: "Accord", year: 1998 };"make" in mycar; // 返回 true"model" in mycar; // 返回 true

in右操作数必须是一个对象值。例如,你可以指定使用String构造函数创建的字符串,但不能指定字符串文字。

js
var color1 = new String("green");"length" in color1; // 返回 truevar color2 = "coral";"length" in color2; // 报错 (color2 不是对象)

对被删除或值为 undefined 的属性使用in

如果你使用delete 运算符删除了一个属性,则in 运算符对所删除属性返回false

js
var mycar = { make: "Honda", model: "Accord", year: 1998 };delete mycar.make;"make" in mycar; // 返回 falsevar trees = new Array("redwood", "bay", "cedar", "oak", "maple");delete trees[3];3 in trees; // 返回 false

如果你只是将一个属性的值赋值为undefined,而没有删除它,则in 运算仍然会返回true

js
var mycar = { make: "Honda", model: "Accord", year: 1998 };mycar.make = undefined;"make" in mycar; // 返回 true
js
var trees = new Array("redwood", "bay", "cedar", "oak", "maple");trees[3] = undefined;3 in trees; // 返回 true

继承属性

如果一个属性是从原型链上继承来的,in 运算符也会返回true

js
"toString" in {}; // 返回 true

规范

Specification
ECMAScript® 2026 Language Specification
# sec-relational-operators

浏览器兼容性

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp