在 ActionsScript/Flex 中测试未定义和 null 子对象

发布于 2024-09-02 08:11:44 字数 354 浏览 1 评论 0原文

我使用此模式来测试 ActionScript/Flex 中的未定义值和空值:

if(obj) {
    execute()
}

不幸的是,当我使用该模式测试子对象时,总是会抛出 ReferenceError :

if(obj.child) {
    execute()
}

ReferenceError: Error #1069: Property child not found on obj and there is no default value.

为什么使用 if 语句测试子对象会抛出 ReferenceError?

谢谢!

I use this pattern to test for undefined and null values in ActionScript/Flex :

if(obj) {
    execute()
}

Unfortunately, a ReferenceError is always thrown when I use the pattern to test for child objects :

if(obj.child) {
    execute()
}

ReferenceError: Error #1069: Property child not found on obj and there is no default value.

Why does testing for child objects with if statements throw a ReferenceError?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

只想待在家 2024-09-09 08:11:44

您收到此错误是因为 obj 的类型中没有 child 属性。您需要执行以下操作:

if((obj) && (obj.hasOwnProperty('child') && (obj.child)){
 execute()
}

有关 Object 类中的 hasOwnProperty 方法的更多信息:
http://livedocs.adobe.com/flex/ 3/langref/Object.html#hasOwnProperty%28%29

You're getting this error because the obj's type does not have the child property in it. You need to do something like this:

if((obj) && (obj.hasOwnProperty('child') && (obj.child)){
 execute()
}

More info on the hasOwnProperty method in the Object class:
http://livedocs.adobe.com/flex/3/langref/Object.html#hasOwnProperty%28%29

天暗了我发光 2024-09-09 08:11:44

obj 是强类型对象但没有 child 字段时,就会发生这种情况。

您可以使用 in 运算符测试任何对象上是否存在字段:

if ("foo" in obj && obj.foo)
    execute();

我还编写了一个实用程序函数来简化此过程:

function getattr(obj:Object, field:*, dflt:*=undefined):* {
    if (field in obj && obj[field])
        return obj[field];
    return dflt;
}

This happens when obj is a strongly typed object but it doesn't have a child field.

You can test to see if a field exists on any object using the in operator:

if ("foo" in obj && obj.foo)
    execute();

I've also written a utility function to make this process easier:

function getattr(obj:Object, field:*, dflt:*=undefined):* {
    if (field in obj && obj[field])
        return obj[field];
    return dflt;
}
灯下孤影 2024-09-09 08:11:44

您可以通过使用数组表示法来避免引用错误:

if([obj.name][child.name]){
execute();
}

要认识到的重要一点是,简单地避免错误可能会导致问题出现 - 在较大的应用程序中调试将更加困难。

当然,理想的方法是通过使用验证器函数来完全避免这种情况,以确保您拥有正确的数据,而不是在需要数据时测试 null。 :)

You can avoid reference errors by using array notation:

if([obj.name][child.name]){
execute();
}

The important thing to realize is that simply avoiding the error can cause issues down the track - debugging will be harder in larger applications.

Of course, the ideal approach is to completely avoid the situation by using validator functions to ensure you have the right data, instead of testing for null when the data is required. :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文