in 运算符

更新:2007 年 11 月

测试一个对象中是否存在一种属性。

property in object

参数

  • property
    必选。计算结果为字符串的表达式。

  • object
    必选。任意对象。

备注

in 运算符检查对象中是否有名为 property 的属性。它还检查对象的原型,以便知道 property 是否为原型链的一部分。如果 property 在对象或原型链中,则 in 运算符返回 true,否则返回 false

in 运算符不应与 for...in 语句混淆。

说明:

若要测试对象本身是否有属性,并且不从原型链中继承属性,请使用对象的 hasOwnProperty 方法。

示例

下面的示例阐释 in 运算符的一种用法。

function cityName(key : String, cities : Object) : String {
   // Returns a city name associated with an index letter.
   var ret : String = "Key '" + key + "'";
   if( key in cities )
      return ret + " represents " + cities[key] + ".";
   else  // no city indexed by the key
      return ret + " does not represent a city."
}

// Make an object with city names and an index letter.
var cities : Object = {"a" : "Athens" , "b" : "Belgrade", "c" : "Cairo"}

// Look up cities with an index letter.
print(cityName("a",cities));
print(cityName("z",cities));

该代码的输出为:

Key 'a' represents Athens.
Key 'z' does not represent a city.

要求

版本 1

请参见

概念

运算符优先级

运算符摘要

参考

for...in 语句

hasOwnProperty 方法