Coffeescript 创建哈希表
Coffescript creating a hashtable
在下面的代码段中,我尝试使用名为 "one" 的单个键创建哈希表,并将相同的值 "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' ] }
这是一个fiddle:
http://jsfiddle.net/u4wpg4ts/
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))
在下面的代码段中,我尝试使用名为 "one" 的单个键创建哈希表,并将相同的值 "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' ] }
这是一个fiddle: http://jsfiddle.net/u4wpg4ts/
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))