我对此代码有疑问:
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
我不明白如何从一个变量分配两个值。
元素必须是数组才能使上面的内容成功地将值分配给左侧数组吗?
最佳答案
I do not understand how I can assign two values from one variable.
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];
Would element have to be an array in order for the above to successfully assign values to the left hand side array?
不,它也可以用于对象。来自 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]);
关于javascript - CoffeeScript 作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12048654/