2015-04-14 58 views
1

在下面的代碼段中,我試圖用一個名爲「one」的鍵創建一個散列表,並將相同的值「ted」推送到一個數組中。Coffescript創建散列表

out = {}; 
for i in [1..10] 
    key = "one"; 
    if(key not in out) 
    out[key] = []; 
    out[key].push("ted") 
    console.log("pushing ted"); 

console.log(out); 

我錯過了什麼?看來這個輸出是:

pushing ted 
pushing ted 
pushing ted 
pushing ted 
pushing ted 
pushing ted 
pushing ted 
pushing ted 
pushing ted 
pushing ted 
{ one: [ 'ted' ] } 

我希望可以將輸出爲:

pushing ted 
pushing ted 
pushing ted 
pushing ted 
pushing ted 
pushing ted 
pushing ted 
pushing ted 
pushing ted 
pushing ted 
{ one: [ 'ted','ted','ted','ted','ted','ted','ted','ted','ted','ted' ] } 

這裏是一個小提琴: http://jsfiddle.net/u4wpg4ts/

回答

3

CoffeeScript中的in關鍵字並不意味着一樣它在JavaScript中完成。它將檢查是否存在值而不是密鑰。

# coffee 
if (key not in out) 
// .js (roughly) 
indexOf = Array.prototype.indexOf; 

if (indexOf.call(out, key) < 0) 

由於密鑰("one")是從來沒有存在於所述陣列作爲值("ted"),條件總是通過。所以,在每個.push()之前,該陣列將被替換並重置爲空。

CoffeeScript中的of keyword反而會檢查該鍵的存在,只應第一時間傳遞:

# coffee 
if (key not of out) 
// .js 
if (!(key in out)) 
+1

你也可以'出[關鍵] = []'或'出[?鍵] || = []'而不是'if'。甚至是'(out [key]?= [])。push('ted')'或者(out [key] || = [])。push('ted')'。 –