【问题标题】:In Actionscript 3 what is the best way to test if a string is a property of an object在 Actionscript 3 中,测试字符串是否是对象的属性的最佳方法是什么
【发布时间】:2011-07-02 01:19:06
【问题描述】:

我通常通过询问来测试字符串是否是对象中的键:

var foo:Object = {bar:"bar", bah:["bah","bah1"]};
var str:String = "boo";
if(foo[str]) // do something

但是如果 str == "constructor" 它会做一些事情 - 因为 foo["constructor"] 无论如何都会返回 true。

测试字符串是否是对象的键的最佳方法是什么 - 并且对于构造函数不返回 true?

一些例子:

var foo:Object = {bar:"bar", bah:["bah","bah1"]};
trace('foo["bar"]: ' + foo["bar"]);
trace('foo["bah"]: ' + foo["bah"]);
trace('foo["constructor"]: ' + foo["constructor"]);
trace('foo["bar"] == true: ' + (foo["bar"] == true));
trace('foo["bah"] == true: ' + (foo["bah"] == true));
trace('foo["constructor"] == true: ' + (foo["constructor"] == true));
if(foo["bar"]){
    trace("foo:bar");
}
if(foo["bah"]){
    trace("foo:bah");
}
if(foo["constructor"]){
    trace("foo:constructor");
}
trace('"constructor" in foo: ' +  ("constructor" in foo));

痕迹:

/*
foo["bar"]: bar
foo["bah"]: bah,bah1
foo["constructor"]: [class Object]
foo["bar"] == true: false
foo["bah"] == true: false
foo["constructor"] == true: false
foo:bar
foo:bah
foo:constructor
"constructor" in foo: true
*/

【问题讨论】:

    标签: object actionscript constructor


    【解决方案1】:

    如果它是一个具体的类实现,你应该能够在很大程度上摆脱hasOwnProperty

    var hasProperty : Boolean = foo.hasOwnProperty("bar");
    

    这显然也应该适用于匿名对象(感谢您让我知道!)。

    【讨论】:

    • hasProperty 工作:foo.hasOwnProperty("bar"):truefoo.hasOwnProperty("constructor"):false
    • 感谢您告诉我,我已更新我的答案以删除不必要的内容。
    猜你喜欢
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    • 2015-08-23
    • 1970-01-01
    相关资源
    最近更新 更多