花括号内的变量启动[重复](Variable initiation inside curly braces [duplicate])

这个问题在这里已有答案:

指定 4个答案 左侧的Javascript对象括号表示法({Navigation} =)

这段代码转化为什么? 我无法弄清楚花括号内的变量如何与= require('react-router') 。

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

它来自这个回购

This question already has an answer here:

Javascript object bracket notation ({ Navigation } =) on left side of assign 4 answers

What does this code translate to? I can't figure out how the variables inside the curly braces are related to = require('react-router').

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

It is from this repo

最满意答案

这是ES6中称为解构赋值的功能。 这是发生的事情:

// 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

This is a feature called destructuring assignment in ES6. This is what happens:

// 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

更多推荐