2015-04-14 57 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')'。 –