测试一个对象中是否存在一种属性。
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.要求请参见
参考
for...in 语句hasOwnProperty 方法
概念
运算符优先级运算符摘要