有没有办法从 CoffeeScript 的理解中返回一个对象?一些东西,以便我可以表达这一点:
form_values = () ->
ret = {}
ret[f.name] = f.value for f in $('input, textarea, select')
return ret
像这样:
form_values = () -> f.name, f.value for f in $('input, textarea, select')
我想构造一个对象(不是对象数组)。所以如果标记看起来像这样:
<form name=blah>
<input type=text name=blah1 value=111 />
<textarea name=blah2>222</textarea>
<select name=blah3>
<option value=333a>
<option value=333b>
</select>
</form>
返回的对象将是这样的:
{
blah1: '111',
blah2: '222',
blah3: ''
}
最佳答案
form_values = new ->
@[f.name] = f.value for f in $ 'input, textarea, select'
this
或者
form_values = new class then constructor: ->
@[f.name] = f.value for f in $ 'input, textarea, select'
关于coffeescript - CoffeeScript 中的理解对象 [dict/hash comprehensions],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7949564/