我有一个关于这段代码的问题:
getContent: (index) ->
content = @get('content')
element = content.objectAt(index)
if element?
[type, clientId] = element
store = @get('store')
if clientId?
store.findByClientId(type, clientId)我特别说的是这一行:
[type, clientId] = element我不明白如何从一个变量中分配两个值。
元素必须是一个数组才能成功地将值赋给左边的数组吗?
发布于 2012-08-21 13:08:12
这就是语法糖,意思是:
type = element[0], clientId = element[1];另外,你应该知道,有一个地方你可以在编译的coffeescript中看到:http://coffeescript.org/ (try coffeescript标签)
所有的coffeescript代码都在javascript中:
getContent: function(index) {
var clientId, content, element, store, type;
content = this.get('content');
element = content.objectAt(index);
if (element != null) {
type = element[0], clientId = element[1];
store = this.get('store');
if (clientId != null) {
return store.findByClientId(type, clientId);
}
}
}发布于 2012-08-21 13:29:09
我不明白如何从一个变量中分配两个值。
CoffeeScript实现了它所谓的Destructuring Assignment。在http://coffeescript.org/#destructuring上可以看到完整的解释,但我在这里引用了一些示例。
它可以用于简单的列表赋值。
weatherReport = (location) ->
# Make an Ajax request to fetch the weather...
[location, 72, "Mostly Sunny"]
[city, temp, forecast] = weatherReport "Berkeley, CA"其中解构赋值语句被编译为
_ref = weatherReport("Berkeley, CA"), city = _ref[0],
temp = _ref[1], forecast = _ref[2];元素必须是一个数组才能成功地将值赋给左边的数组吗?
不,它也可以用于对象。从CoffeeScript文档“解构赋值可以用于任何深度的数组和对象嵌套,以帮助提取深度嵌套的属性。”
futurists =
sculptor: "Umberto Boccioni"
painter: "Vladimir Burliuk"
poet:
name: "F.T. Marinetti"
address: [
"Via Roma 42R"
"Bellagio, Italy 22021"
]
{poet: {name, address: [street, city]}} = futurists其中解构赋值语句被编译为
_ref = futurists.poet,
name = _ref.name, (_ref1 = _ref.address, street = _ref1[0], city = _ref1[1]);https://stackoverflow.com/questions/12048654
复制相似问题