我不明白如何从一个变量中分配两个值。
CoffeeScript 实现了它所谓的解构赋值。请参阅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]);