2012-09-24 44 views
1
b 

if b? 

轉變爲「未定義」 中的CoffeeScript

b; 

if (typeof b !== "undefined" && b !== null) 

如果我設置b = [],我得到if (b != null) {

哪裏undefined?捕獲未定義的數組(在唯一之後)是個問題。

當我做

a = [1,1,2,2,3,3,4,444,4,4,4] 
a.unique() 

我能得到這樣的:

a = [1,2,3,4,444,undefined] 

我不能趕上這一點,因爲萬一a?[key] - 我只拿到了檢查!= null

我必須做什麼?

回答

2

我沒有看到問題。 undefined == null在JavaScript中是正確的,並且undefined != null是錯誤的,所以if(b != null)涵蓋b === undefined的情況。事情是這樣的:

a = [ undefined ] 
if(a[0]?) 
    console.log('if') 
else 
    console.log('else') 

會產生else預期在控制檯上,所以會這樣:

a = undefined 
if(a?[0]) 
    console.log('if') 
else 
    console.log('else') 
+0

我用這個函數[鏈接](http://coffeescriptcookbook.com/chapters後看問題/ arrays/removed-duplicate-elements-from-arrays)只有當我像下面這樣「修復」時,我會得到類似[「11」,「12」,「13」,「undefined」]的內容:'輸出值爲 result.push value if value?和value!=「undefined」我得到的結果沒有「undef ..」 – Vladislav

+0

所以你的* string *''undefined''在你的數組中? –

+0

嘗試使用字符串轉換。 當與「未定義」 –

相關問題