在下面的代码段中,我尝试使用名为&#34的单个键创建一个哈希表;一个"并推动相同的价值" ted"成阵列。
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/
答案 0 :(得分: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))