2014-03-27 25 views
0

的陣列則存在可以是整數或整數的陣列的變種。我想有一個檢查,當var不爲null或其數組元素爲null時返回true。該變種可以是:如何檢查變種是空時,它可以是空值

a = null 

a = [null, null] 

支票

if (a != null) 

返回true時

a = [null, null] 

我想避免這種情況。我怎樣才能做到這一點,最好是coffescript。

+2

嘗試'如果(a.indexOf(空)== -1)' – elclanrs

+0

使用UNDEFINE當你想要一個未定義的整數,空始終是一個空對象 –

回答

1

如果我用(a.indexOf(空)== -1)。謝謝!

0

您可以檢查如下:以下情況將被要求從elclanrs測試

if(a != null) 

if (typeof a[index] !== 'undefined' && a.indexOf(null) == -1) 

if (a[index] != null) 
0
if (a instanceof Array) { 
    //check each index of a 
} else { 

    //check only the a 
} 
0

嗯,我想這取決於數組中的單個null是否足以使檢查失敗。例如,[1,3,5,null,9]足以讓上面的IF檢查返回true?如果是這樣,那麼上述建議將起作用。如果沒有,那麼你可能會想要做這樣的事情:

Array.prototype.unique = [].unique || function (a) { 
    return function() { 
     return this.filter(a) 
    }; 
}(function(a,b,c) { 
    return c.indexOf(a,b + 1) < 0 
}); 
var nullArray = [null, null, null, null], 
    notNullArray = [null, 1, null, 2], 
    filtered; 

if((filtered = nullArray.unique()) && (filtered.length == 1) && (filtered[0] == null)) { 
    // NULL VALUE 
    alert('NULL!') 
} else { 
    // SAFE TO WORK WITH 
    alert('NOT NULL!') 
} 

if((filtered = notNullArray.unique()) && (filtered.length == 1) && (filtered[0] == null)) { 
    // NULL VALUE 
    alert('NULL!') 
} else { 
    // SAFE TO WORK WITH 
    alert('NOT NULL!') 
} 

如果長度大於1,那麼它絕對不是隻包含空值。

日Thnx,
克里斯托夫