javascript:变量名之间花括号的含义

javascript: meaning of curly brace between variable name

我对 javascript 非常无能,因为它的语法很松散,但对特殊字符的含义非常惩罚。

react-native-navigation tutorial 中有这个片段

static navigationOptions = ({ navigation }) => {
   const {state, setParams} = navigation;
   const isInfo = state.params.mode === 'info';
   const {user} = state.params;
   return {
     title: isInfo ? `${user}'s Contact Info` : `Chat with 
 ${state.params.user}`,
     headerRight: (
       <Button
         title={isInfo ? 'Done' : `${user}'s info`}
         onPress={() => setParams({ mode: isInfo ? 'none' : 'info'})}
       />
     ),
   };
 };

原来,我把第三行误打成这样: const {isInfo} = state.params.mode === 'info';

我的代码不起作用。

有什么区别: const isInfo = state.params.mode === 'info';

从下一行开始,有花括号包裹{user}

这让我很困惑,但是这种小事是出了名的难Google,所以很抱歉,提前谢谢!

在 ES6 中,您可以将对象解构为不同的变量。您可以阅读更多相关信息 here

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

像你提到的本质上是花括号是 javascript 中的对象。

所以在 javascript

中制作这样的东西
const user = {
    name: 'bob',
    age: 23,
};

正在创建一个用户对象,您可以像这样使用它:user.name 这将 return bob.

使用 ES6,您可以从其他对象创建对象。

const {user} = state.params;
//user will be state.params.user

上面基本上是将对象state.params中的属性user拉到一个新变量中。实际上,他们所做的就是做到这一点,这样您就不必每次都写 state.params.user,而是可以写 user.

您可以使用上述技术做一些其他很酷的事情。您可以 'merge' 数组和对象转换为新常量,这非常酷。

const test = {
    ...user,
    anotherProperty: 'value',
};

使用 react 和 redux(如果你正在使用它)你会看到很多这样的东西:Object.assign({}, state, {}); 用于创建一个新对象,状态的先前属性被新的覆盖状态(因为 redux 需要一个新对象)。这有点像使用 {...state, ...newState}

请有人提醒我这个 ...Object 方法叫什么?

这一行 const isInfo = state.params.mode === 'info'; 是 shorthand 用于声明布尔值。 isInfo 为真或假取决于 state.params.mode === 'info'.

为您将以上翻译成C++

if (state.params.mode === 'info') {
    bool isInfo = true;
else {
    bool isInfo = false;
}

我不记得在 C++ 中是否有与 JavaScript 中类似的对象数组,有点认为 JavaScript 中的对象是具有定义键的数组。这样上面的 {...state, ...newState} 就像一个 'override' 键。所以

int y = [1,2,3];
int x = [3,2,1];


for (i=0;i<=2;i++) {
    y[i] = x[i];
}

我觉得是这样的?

这是 ES6 语法,表达式 const {user} = state.params; 等于 const user = state.params.user;const {isInfo} = state.params.mode === 'info'; 将导致 {isInfo: undefined}。 有关详细信息,请参阅 here.