什么是“......”在Javascript(ES6)中意味着什么? [英] What "..." means in Javascript (ES6)?

查看:93
本文介绍了什么是“......”在Javascript(ES6)中意味着什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Redux,React和ES6。我已经用JS开发了,但是这个ES6的新世界让我很惊讶,有许多新的东西,比如=>来声明箭头函数和其他。但是,在这个新的Redux研究中,我在代码中间遇到了 ...

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我有一个例子:

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

如果我更换

state = {.. .state,name:action.payload};


state = {... state,age:action.payload};

with

state.name = action.payload;


state.age = action.payload;

它有效,但年龄被一起插入对象名称,在第一种情况下插入名称并插入年龄后。

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?

推荐答案

这就是所谓的传播运营商

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

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

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

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

这篇关于什么是“......”在Javascript(ES6)中意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆