【问题标题】:Variable initiation inside curly braces [duplicate]花括号内的变量起始[重复]
【发布时间】:2015-02-23 01:40:12
【问题描述】:

这段代码翻译成什么?我无法弄清楚花括号内的变量与= require('react-router') 的关系。

var { create: createRouter, HistoryLocation, HashLocation } = require('react-router')

来自this repo

【问题讨论】:

  • 解构赋值。

标签: javascript reactjs commonjs


【解决方案1】:

这是 ES6 中称为 destructuring assignment 的功能。这就是发生的事情:

// Imagine this is the object you require
var reactRouter = {
  create: 'foo',
  HistoryLocation: 'bar',
  HashLocation: 'baz'
}

// Destructure
var {create: createRouter, HistoryLocation, HashLocation} = reactRouter

// Now the variables are in scope
console.log(createRouter, HistoryLocation, HashLocation)
//^ foo, bar, baz

【讨论】:

  • 很好的解释。看起来很有趣!谢谢
【解决方案2】:

看起来它是解构赋值。它是Javascript ES6 and is described here.的一部分

解构赋值语法是一种 JavaScript 表达式,可以使用反映数组和对象字面量构造的语法从数组或对象中提取数据。

很酷的新功能!我期待着使用它。

【讨论】:

    猜你喜欢
    • 2014-11-26
    • 2020-09-28
    • 2018-05-31
    • 1970-01-01
    • 2017-07-25
    • 2014-11-23
    • 1970-01-01
    • 2020-01-09
    • 2019-02-16
    相关资源
    最近更新 更多