What “…” means in Javascript (ES6)? [duplicate]

2019-02-10 05:19发布

This question already has an answer here:

I am learning Redux, React and ES6. I already developed with JS, but this new world of ES6 are surprising me with a lot of new things like "=>" to declare arrow functions and other. However, in this new Redux studies, I confront with ... in middle of my code.

Bellow I have an example:

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});

If I replace
state = {...state, name: action.payload}; and
state = {...state, age: action.payload};
with
state.name = action.payload; and
state.age = action.payload;
it works, but the age was inserted into object together name and in first case the name was inserted and after age was inserted.

Why does it happen? How can I use ... in my future codes? Is it just in related with states?

1条回答
疯言疯语
2楼-- · 2019-02-10 05:46

That's called the spread operator.

It unpacks values from an object or array, into another object or array. For example, using arrays:

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

The same semantics apply to objects:

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

You can use it to shallow-copy objects and arrays:

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

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

Check out the Mozilla docs, an excellent source for all things javascript.

查看更多
登录 后发表回答