2008-09-18 107 views

回答

37

如果它是一個對象,那麼你就應該能夠進行檢查,看它是否是nullundefined,然後加載它,如果它是。

if (myObject === null || myObject === undefined) { 
    myObject = loadObject(); 
} 

使用typeof函數也是一個選項,因爲它返回提供的對象的類型。但是,如果該對象尚未加載,它將返回null or undefined,因此在可讀性方面它可能會歸結爲個人偏好。

+1

不是像if (myObject == null)(或未定義)就夠了,因爲這恰恰是簡單相等的一點?或者我錯過了什麼? – PhiLho 2008-12-03 14:19:51

1

typeof(obj)將返回「對象」用於其他可能的值中的類的對象。

27
if(typeof(o) != 'object') o = loadObject(); 
+9

請記住,typeof返回「對象」的空值,所以你可能會想要類似[if(null!== x &&'object'== typeof(x)){] – 2008-09-18 23:10:52

3

我不確定你的意思是「加載」......變量object是否存在並且根本沒有你想要的類型?在這種情況下,您需要類似的東西:

function isObjectType(obj, type) { 
    return !!(obj && type && type.prototype && obj.constructor == type.prototype.constructor); 
} 

然後使用if (isObjectType(object, MyType)) { object = loadObject(); }

如果object沒有測試之前與任何填充(即 - typeof object === 'undefined'),那麼你只需要:

if ('undefined' === typeof object) { object = loadObject(); } 
3

你可能想看看一個給定的對象定義

特別是如果它在具有setTimeout的異步線程中完成,以檢查它何時啓動。

var generate = function() 
    { 
     window.foo = {}; 
    }; 
    var i = 0; 
    var detect = function() 
    { 
    if(typeof window.foo == "undefined") 
    { 
      alert("Created!"); 
      clearInterval(i); 
    } 
    }; 
    setTimeout(generate, 15000); 
    i = setInterval(detect, 100); 

理論上應該檢測window.foo何時存在。

2

如果要檢測一個自定義對象:

// craete a custom object 
function MyObject(){ 

} 

// check if it's the right kind of object 
if(!(object instanceof MyObject)){ 
    object = new MyObject(); 
} 
3

如果加載你的意思是定義,你可以使用typeof檢查變量的類型功能。 無論其的typeof有幾個怪癖,並將確定的對象,數組和爲對象

alert(typeof(null)); 

確定一個null作爲一個定義的對象可能會導致程序出現故障,所以檢查喜歡的東西

if(null !== x && 'object' == typeof(x)){ 
    alert("Hey, It's an object or an array; good enough!"); 
} 
4
myObject = myObject || loadObject(); 
1
if (!("someVar" in window)) { 
    someVar = loadObject(); 
} 

會告訴你任何JS之前是否已經分配給格洛巴l someVar或宣佈頂級var someVar

即使加載值爲undefined,也可以工作。

相關問題