CoffeeScript RegEx ListComprehension与Dictionary对象/数组

CoffeeScript RegEx ListComprehension with Dictionary-Object / Array

本文关键字:对象 数组 Dictionary RegEx ListComprehension CoffeeScript      更新时间:2023-09-26

代码

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注册Ex,例如,如果mattazz密钥在list中,则检索值"Honey"。

您正试图遍历对象,但您的coffee语法用于数组迭代。为此,您需要of关键字。(参见Coffescript.org:循环与理解(

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