在读取属性值之前如何测试对象上是否存在属性?
我正在尝试读取一系列精灵的属性。该属性可能存在于这些对象上,也可能不存在,甚至可能没有声明,比 null 更糟糕。
我的代码是:
if (child["readable"] == true){
// this Sprite is activated for reading
}
Flash 向我展示了:
错误#1069:在 flash.display.Sprite 上找不到可选择的属性,并且没有默认值。
有没有办法在读取属性值之前测试属性是否存在?
像这样的东西:
if (child.isProperty("readable") && child["readable"] == true){
// this Sprite is activated for reading
}
I'm attempting to read a property on a series of Sprites. This property may or may not be present on these objects, and may not even be declared, worse than being null.
My code is:
if (child["readable"] == true){
// this Sprite is activated for reading
}
And so Flash shows me:
Error #1069: Property selectable not found on flash.display.Sprite and there is no default value.
Is there a way to test if a property exists before reading its value?
Something like:
if (child.isProperty("readable") && child["readable"] == true){
// this Sprite is activated for reading
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
AS3 中的对象具有
hasOwnProperty
方法,它接受一个字符串参数,如果对象定义了该属性,则返回true
。Objects in AS3 have the
hasOwnProperty
method which takes a string argument and returnstrue
if the object has that property defined.添加此内容是因为它是 Google 中的热门回复。
如果您尝试使用字符串作为名称来检查常量是否存在,请使用
Adding this as it is a top response in Google.
If you are trying to check if a constant exists using a string for the name then use
尝试这样的事情:
Try something like this:
对@Vishwas G的回应(不是评论,因为评论中不支持代码块):
正如丹尼尔指出的那样,如果您的示例中的对象“a”首先不存在,那么您将尝试访问“b”在“a”上会导致错误。这种情况发生在您期望深层结构的情况下,例如可能具有“content.social.avatar”格式的 JSON 对象。如果“social”不存在,则尝试访问“content.social.avatar”将导致错误。
下面是深层结构属性存在性测试的一般情况示例,其中“未定义”方法可能会在“hasOwnProperty()”方法不会导致错误的情况下导致错误:
现在进行测试...
请注意,ActionScript 的同级语言 JavaScript在 test1 示例中不会生成错误。但是,如果将对象层次结构再扩展一层,您也会在 JavaScript 中遇到错误:
Response to @Vishwas G (not a comment because code blocks aren't supported in comments):
As Daniel pointed out, if the object "a" in your example doesn't exist in the first place, your attempt to access "b" on "a" will cause an error. This happens in cases where you're expecting a deep structure, such as a JSON object that might, for example, have the format "content.social.avatar". If "social" doesn't exist, then attempting to access "content.social.avatar" will cause an error.
Here's a general-case example of a deep-structure property-existence test where the "undefined" approach can cause an error in cases where the "hasOwnProperty()" approach does not:
Now the tests...
Note that ActionScript's sibling language JavaScript would not generate an error in the test1 example. However, if you extend the object hierarchy one more level, you'll bump into errors in JavaScript too: