我对此代码有疑问:
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
我不明白如何从一个变量中分配两个值。
元素必须是一个数组,以便上面成功地将值赋给左侧数组吗?
答案 0 :(得分:4)
我不明白如何从一个变量中分配两个值。
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]);
答案 1 :(得分:0)
那是语法糖,意思是:
type = element[0], clientId = element[1];
另外,你应该知道,有一个地方你可以看到coffeescript编译的内容:http://coffeescript.org/(试试coffeescript标签)
javascript中的所有coffeescript代码:
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);
}
}
}