2010-05-02 72 views
27

我試圖在一系列精靈的讀取性能。這個屬性可能會或可能不會出現在這些對象上,甚至可能不會被聲明,比空值更糟。如何在讀取對象之前測試對象是否存在屬性?

我的代碼是:

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

所以閃光顯示我:

錯誤#1069:屬性選擇不flash.display.Sprite發現沒有默認值。

有沒有辦法在讀取它的值之前測試某個屬性是否存在?

是這樣的:在AS3

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

回答

53

對象具有hasOwnProperty方法,該方法需要一個字符串參數,並返回true如果對象屬性定義具有。

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

嘗試是這樣的:

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

} 
+4

如果第一個位置不存在,則會導致錯誤。你會看到錯誤如果要創建一個對象動態像尋找一個[ 「b」 的]在'VAR一個:對象= {A: '1'}' – Daniel 2013-03-22 18:16:59

+0

(這是不工作) – Lego 2014-01-14 18:25:44

+0

VAR一個; a = a {a:1}; trace(a [「b」]),輸出「undefined」,但不會產生任何錯誤。那麼,使用這種方式的問題在哪裏? – 2014-08-16 17:15:39

17
if ("readable" in child) { 
    ... 
1

添加這個,因爲它是在谷歌頂部響應。

如果你想檢查是否存在一個常數使用名稱的字符串,然後使用

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

響應@Vishwas G(不評論,因爲代碼塊中不支持的意見):

由於丹尼爾指出,如果對象「一」在你的例子並不在首位存在,您嘗試訪問「b」上「的」會導致錯誤。這發生在你期待一個深層結構,如JSON對象可能,例如,具有格式「content.social.avatar」的情況。如果「社交」不存在,則嘗試訪問「content.social.avatar」將導致錯誤。

這裏有一個深刻的結構特性,存在測試的一個普通案例,其中「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 
相關問題