CoffeeScript RegEx ListComprehension与Dictionary-Object / Array

时间:2015-08-03 10:17:35

标签: javascript regex coffeescript

代码

list = {}
list['blubber'] = 'it blubbers'
list['Bearmattazz'] = 'Honey'
document.write list.blubber

result = (item for item in list when item.match(/(mattazz)/g))
document.write '<br>Res: ', result

http://codepen.io/anon/pen/OVrwKO

需要

我想要mattazz的regEx,例如检索值&#34; Honey&#34;,以防mattazz密钥位于list

1 个答案:

答案 0 :(得分:1)

您正在尝试遍历对象,但您的咖啡语法适用于数组迭代。您需要 of 关键字。 (见Coffescript.org: Loops and Comprehensions

list是一个对象(如在键值存储中),因此您要使用key, value of list

list = {}
list['Bearmattazz'] = 'Honey'

# in case you want to retrieve value
#
result = (value for key, value of list when key.match(/(mattazz)/g))

# in case you want to retrieve key
#
result = (key for key, value of list when key.match(/(mattazz)/g))

document.write '<br>Res: ', result