非常教程

JavaScript参考手册

Operators

in

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

语法

prop in object

参数

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

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

描述

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

// Arrays
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
0 in trees        // returns true
3 in trees        // returns true
6 in trees        // returns false
'bay' in trees    // returns false (you must specify the 
                  // index number, not the value at that index)
'length' in trees // returns true (length is an Array property)
Symbol.iterator in trees // returns true (arrays are iterable, works only in ES2015+)

// Predefined objects
'PI' in Math          // returns true

// Custom objects
var mycar = {make: 'Honda', model: 'Accord', year: 1998};
'make' in mycar  // returns true
'model' in mycar // returns true

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

var color1 = new String('green');
'length' in color1 // returns true

var color2 = 'coral';
// generates an error (color2 is not a String object)
'length' in color2

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

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

var mycar = {make: 'Honda', model: 'Accord', year: 1998};
delete mycar.make;
'make' in mycar;  // returns false

var trees = new Array('redwood', 'bay', 'cedar', 'oak', 'maple');
delete trees[3];
3 in trees; // returns false

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

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

继承属性

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

'toString' in {}; // returns true

规范

Specification

Status

Comment

ECMAScript Latest Draft (ECMA-262)The definition of 'Relational Operators' in that specification.

Living Standard

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Relational Operators' in that specification.

Standard

ECMAScript 5.1 (ECMA-262)The definition of 'The in Operator' in that specification.

Standard

ECMAScript 3rd Edition (ECMA-262)The definition of 'The in Operator' in that specification.

Standard

Initial definition. Implemented in JavaScript 1.4.

浏览器兼容性

Feature

Chrome

Firefox (Gecko)

Edge

Internet Explorer

Opera

Safari

Basic support

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

Feature

Android

Chrome for Android

Edge

Firefox Mobile (Gecko)

IE Mobile

Opera Mobile

Safari Mobile

Basic support

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

JavaScript

JavaScript 是一种高级编程语言,通过解释执行,是一门动态类型,面向对象(基于原型)的解释型语言。它已经由ECMA(欧洲电脑制造商协会)通过 ECMAScript 实现语言的标准化。它被世界上的绝大多数网站所使用,也被世界主流浏览器( Chrome、IE、FireFox、Safari、Opera )支持。JavaScript 是一门基于原型、函数先行的语言,是一门多范式的语言,它支持面向对象编程,命令式编程,以及函数式编程。它提供语法来操控文本、数组、日期以及正则表达式等,不支持 I/O,比如网络