2017-09-15 74 views
1

由於其寬鬆的語法,但對於特殊字符的含義非常嚴格,所以我對javascript非常虛弱。javascript:變量名稱之間的大括號的含義

react-native-navigationtutorial有此片段

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}

這對我來說是非常混亂,但是這幾樣小的事情是非常困難的谷歌,很抱歉,並提前感謝!

+2

請檢查本參考鏈接:https://stackoverflow.com/questions/26999820/javascript-object-bracket-notation-navigation-on-left-side-of-assign –

回答

5

像你提到的基本上花括號是javascript中的對象。

所以使得這樣的事情在JavaScript

const user = { 
    name: 'bob', 
    age: 23, 
}; 

是使你可以用這樣的用戶對象:user.name將返回bob

使用ES6,您可以從其他對象製作對象。

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

上面基本上是從物體state.params拉動屬性user到一個新的變量。真的,他們正在做的是讓你每次都不用寫state.params.user,而你可以寫user

還有一些其他很酷的東西,你可以用這種技術做。你可以將數組和對象合併成新的常量,這很酷。

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

有了反應,終極版(如果你使用它),你會看到很多這樣的:Object.assign({}, state, {});這是用來創建新對象與新狀態覆蓋國家的前面性質(因爲redux需要一個新的對象)。這與使用{...state, ...newState}的情況相同。

請有人提醒我這個...Object方法被調用?

此行const isInfo = state.params.mode === 'info';是聲明bool的簡寫。根據是否state.params.mode === 'info'isInfo將爲真或假。

要翻譯成以上的C++爲您

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

我不記得是否有在C相似的對象數組++作爲在JavaScript位認爲JavaScript對象與定義鍵陣列。這樣上面的{...state, ...newState}就像是一個'重寫'鍵。所以

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


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

這樣的事情我覺得呢?

+0

我明白了!這是一個非常明確的解釋!非常感謝你! – Zennichimaro

+1

@Zennichimaro我不太喜歡這個名字,因爲你可以告訴^^^這個ES6 env,所以我知道你的感受! (y) – sourRaspberri

+0

哈哈,是的。有很多我看到的JavaScript中的東西,我不明白,但不能谷歌! (是的,我用的是REDX !!)哦,不......我也沒有得到你'高級'的東西,希望有人提醒你,哈哈 – Zennichimaro

4

在ES6中,您可以將對象解構爲不同的變量。可以進一步瞭解它here

的解構賦值語法是JavaScript表達式 使得能夠從 對象解包從數組值或屬性,爲不同的變量。

3

這是ES6語法,表達式const {user} = state.params;等於const user = state.params.user;,並且const {isInfo} = state.params.mode === 'info';將導致{isInfo: undefined}。 欲瞭解更多信息,你可以看到here

相關問題