javascript - CoffeeScript 作业

标签 javascript coffeescript

我对此代码有疑问:

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/

相关文章:

ios - 这个地理定位计算有多准确?

javascript - 为什么缺少模板/组件不会在 Ember.js 中引发错误?

javascript - iOS UIWebView 应用程序在 Safari 中打开链接

javascript - MathUtils.euclideanModulo 的用途是什么?它与常规模数有何不同?

javascript - util.inherits in coffeescript

node.js - 当我的咖啡文件发生变化时,如何让连接 Assets 重新编译它们?

javascript - FramerJS:重新排序数组

javascript - 在缩放时缩放图像和标记

javascript - 不滚动时隐藏滚动条(类似 Mac 的行为)

javascript - 使用 ng-include 和 ng-click 更新数据