根據該:http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7f9f.html引用:無類型變量對對象有什麼好處? null和undefined有什麼區別?
一個無類型變量是不一樣的Object類型的變量。關鍵的區別在於非類型化變量可以保持特定值未定義,而類型爲Object的變量不能保存該值。
但是當我測試它:
var objTest:Object = 123;
var untypedTest:* = 123;
objTest = undefined;
untypedTest = undefined;
//This is understandable but why was the assignment even allowed?
trace(objTest); // prints null
trace(untypedTest); // prints undefined
objTest=null;
untypedTest = null;
//This is also understandable ... both can store null
trace(objTest); // prints null
trace(untypedTest); // prints null
//If they are null whey are they being equal to undefined?
if(objTest==undefined)
trace("obj is undefined");
if(untypedTest==undefined)
trace("untyped is undefined");
//Because null is same as undefined!
if(null==undefined)
trace("null is same as undefined?");
兩個問題:
- 爲什麼賦值爲未定義允許OBJ? (不是一個大問題,因爲它仍然打印爲空)
- 如果我們比較null與未定義的結果true(即使null存儲在Object中)。如果它們相等,則在null和undefined之間做出區別,這有什麼意義?
太棒了...完美的解釋 – basarat
你也使用undefined來檢查一個鍵是否在一個對象中。即'if(myObj [「someKey」] ==未定義)//添加它。 You * could *也可以使用null作爲檢查,但當有人想要將null存儲爲值時,它會中斷。 'myObj [「someKey」] = null; //有效' – divillysausages
@divillysausages,使用'undefined'已棄用。它應該是空的,以防止混淆。如果你需要存儲一個'沒有值'的密鑰,只需使用'0'或'false'(無論如何,密鑰沒有什麼價值?)。 –