如何在读取对象属性值之前测试该属性是否存在?

28

我试图读取一系列Sprites上的一个属性。这个属性可能存在于这些对象上,也可能没有被声明,更糟糕的是可能为null。

我的代码如下:

if (child["readable"] == true){
    // this Sprite is activated for reading
}

因此Flash向我展示:

Error #1069: 在flash.display.Sprite上未找到属性selectable,且没有默认值。

是否有一种方法可以在读取属性值之前测试其是否存在?

例如:

if (child.isProperty("readable") && child["readable"] == true){
    // this Sprite is activated for reading
}
5个回答

59

AS3中的对象具有hasOwnProperty方法,该方法接受一个字符串参数并返回true,如果该对象定义了该属性。

if(myObj.hasOwnProperty("someProperty"))
{
    // Do something
}

18
if ("readable" in child) {
  ...

使用“in”而不是“hasOwnProperty”有什么区别/缺点吗? - OMA
1
如果readablechild的原型中定义而不是实例本身中定义,那么hasOwnProperty将返回false(例如,document.hasOwnProperty('getElementById') === false,而('getElementById' in document) === true)。 - kennytm

1

将此添加为顶部响应的原因是它在Google中排名很高。

如果您想使用字符串来检查常量是否存在,请使用以下方法:

if (ClassName["ConstName"] !== undefined) {
    ...
}

0

回复 @Vishwas G(不是评论,因为代码块不支持在评论中):

正如Daniel所指出的那样,如果你的示例中的对象“a”不存在,那么尝试在“a”上访问“b”将会导致错误。这种情况发生在你期望有一个深层结构的情况下,比如一个JSON对象,它可能具有格式“content.social.avatar”。如果“social”不存在,则尝试访问“content.social.avatar”将会导致错误。

这里是一个通用的深层结构属性存在测试示例,在这种情况下,“undefined”方法可能会导致错误,而“hasOwnProperty()”方法则不会:

// Missing property "c". This is the "invalid data" case.
var test1:Object = { a:{b:"hello"}};
// Has property "c". This is the "valid data" case.
var test2:Object = { a:{b:{c:"world"}}};

现在进行测试...

// ** Error ** (Because "b" is a String, not a dynamic
// object, so ActionScript's type checker generates an error.)
trace(test1.a.b.c);  
// Outputs: world
trace(test2.a.b.c);  

// ** Error **. (Because although "b" exists, there's no "c" in "b".)
trace(test1.a && test1.a.b && test1.a.b.c);
// Outputs: world
trace(test2.a && test2.a.b && test2.a.b.c);  

// Outputs: false. (Notice, no error here. Compare with the previous
// misguided existence-test attempt, which generated an error.)
trace(test1.hasOwnProperty("a") && test1.a.hasOwnProperty("b") && test1.a.b.hasOwnProperty("c"));  
// Outputs: true
trace(test2.hasOwnProperty("a") && test2.a.hasOwnProperty("b") && test2.a.b.hasOwnProperty("c")); 

请注意,ActionScript的兄弟语言JavaScript在test1示例中不会生成错误。但是,如果您将对象层次结构扩展一层,JavaScript也会遇到错误:
// ** Error (even in JavaScript) ** because "c" doesn't even exist, so
// test1.a.b.c.d becomes an attempt to access a property on undefined,
// which always yields an error.
alert(test1.a.b.c.d)

// JavaScript: Uncaught TypeError: Cannot read property 'd' of undefined

0

可以尝试这样做:

if (child["readable"] != null){

}

4
如果对象本身不存在,这可能会导致错误。例如,在动态创建对象时查找类似于var a:Object = {a:'1'}中的a["b"],您将看到错误。请注意:本翻译仅供参考,不保证所有上下文都适用。 - Daniel
变量a; a = a {a:1}; trace(a["b"]),输出"undefined",但不会生成任何错误。那么,使用这种方式的问题在哪里? - Vishwas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接