什么“......”在Javascript(ES6)中意味着什么?

时间:2017-01-25 21:47:56

标签: javascript ecmascript-6 redux

我正在学习Redux,React和ES6。我已经用JS开发了,但是这个ES6的新世界让我很惊讶,有很多新东西,比如“=>”声明箭头功能和其他。但是,在这个新的Redux研究中,我在代码中间与...对峙。

贝娄我有一个例子:

import { combineReducers, createStore } from 'redux'

const userReducer = (state={}, action) => {
    switch(action.type) {
        case 'CHANGE_NAME':
            state = {...state, name: action.payload};
            break;
        case 'CHANGE_AGE':
            state = {...state, age: action.payload};
            break;
    }
    return state;
};

const tweetsReducer = (state=[], action) => {
    return state;
};

const reducers = combineReducers ({
    user: userReducer,
    tweetsReducer: tweetsReducer,
});


const store = createStore(reducers);

store.subscribe(() =>
    console.log('The chage was: ', store.getState())
);

store.dispatch({type: 'CHANGE_NAME', payload: 'Will'})
store.dispatch({type: 'CHANGE_AGE', payload: 21});

如果我更换
state = {...state, name: action.payload};  和
state = {...state, age: action.payload};
 与
state.name = action.payload;  和
state.age = action.payload;
它有效,但年龄被一起插入对象名称,并且在第一种情况下插入名称并插入年龄。

为什么会这样?如何在我的未来代码中使用...?它与国家有关吗?

1 个答案:

答案 0 :(得分:7)

这就是所谓的传播运营商

它将对象或数组中的值解包到另一个对象或数组中。例如,使用数组:

a1  = [1, 2, 3]
a2  = [4, 5, 6]
a12 = [...a1, ...a2] // [1, 2, 3, 4, 5, 6]

相同的语义适用于对象:

o1  = { foo: 'bar' }
o2  = { bar: 'baz' }
o12 = { ...o1, ...o2 } // { foo: 'bar', bar: 'baz' }

您可以使用它来浅层复制对象和数组:

a = [1, 2, 3]
aCopy = [...a] // [1, 2, 3], on a new array

o = { foo: 'bar' }
oCopy = { ...o } // { foo: 'bar' }, on a new object

查看Mozilla docs,这是javascript所有内容的绝佳来源。