我想知道下面的區別(如果有的話):測試的有效性
if(someDOMElement.someProperty)
{
...
if(someDOMElement.someProperty != null)
{
...
if(someDOMElement.someProperty != undefined)
{
...
比其他一個更安全嗎?
我想知道下面的區別(如果有的話):測試的有效性
if(someDOMElement.someProperty)
{
...
if(someDOMElement.someProperty != null)
{
...
if(someDOMElement.someProperty != undefined)
{
...
比其他一個更安全嗎?
這些都會做同樣的事情,並且一個不會比其他人更容易出錯。而如果您使用的是!==
而不是!=
,則只有當值爲null
(第二個)或undefined
(第三個)時,第二個值纔會爲真,因爲!==
算子沒有進行強制轉換。
的JavaScript將與!=
或==
比較過程中強制值,因此,例如:
alert(false == 0); // alerts "true"
alert(false === 0); // alerts "false"
的===
和!==
運營商讓你控制這種行爲。強制出現的規則是detailed in the spec(有點複雜),但只是一個簡單的「這是不是0
,""
,null
或undefined
?」可以簡單地寫成if (thingy)
,它運作良好。 0
,""
,null
和undefined
都是「falsey」。
肖恩金賽has a point關於一些宿主對象,但我想大多數,如果不是所有的DOM元素屬性都會好的。特別是,我看到COM對象表現出一些有趣的行爲,如if (comObject.property)
評估true
當if (comObject.property == null)
也評估true
。 (就我而言,它是作爲我使用的產品的服務器端API的一部分公開的COM對象;我使用Javascript服務器端以及客戶端。)值得注意的是,這可能發生。當你處理Javascript對象和(根據我的經驗)DOM對象時,你很好。
假設someDOMElement不爲空,沒有特別的差異:
http://www.steinbit.org/words/programming/comparison-in-javascript
會有,如果你使用的差異==
根據什麼someDOMElement
是那麼這些可以有很不同的結果,如果涉及到主機對象(例如以ActiveXObjects實現的對象),則它們都不「安全」使用。
你真的應該在http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting
使用的方法,如這些
// use this if you expect a callable property
function isHostMethod(object, property){
var t = typeof object[property];
return t == 'function' ||
(!!(t == 'object' && object[property])) ||
t == 'unknown';
}
// use this if you are only looking for a property
function isHostObject(object, property){
return !!(typeof(object[property]) == 'object' && object[property]);
}
alert(isHostObject(someDOMElement, "someProperty"))
你可以閱讀更多關於適當的特徵檢測一個取決於你所謂的價值。
if(someDOMElement && someDOMElement.someProperty !=undefined){
the property exists and has been set to a value other than undefined or null-
it may be 0, false, NaN or the empty string, as well as any truthy value
}
所以......愚蠢的問題。如果(!someThing)會按預期工作..對嗎? :-) – Konrad 2010-05-24 13:14:43
@Konrad:不是一個愚蠢的問題。是的,會的。你總是看到這樣的事情,例如:'if(!optionalArg){optionalArg = defaultValue; }(儘管你也看到了很多「功能」版本:'optionalArg = optionalArg || defaultValue;')。儘管如此,在使用'false','0','''''等是有效值的args來做這件事時,你需要小心。:-)花了我一個小時,在幾個月後我發現一個錯誤,我很高興地完成了'a = a || 5;'並沒有得到我期望的結果(因爲我傳遞了'a = 0',但當然,然後覆蓋!)。 – 2010-05-24 13:18:47
太好了。感謝真正有用的答案和反饋。 :-) – Konrad 2010-05-24 13:23:41