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

查看:31
本文介绍了什么“……"在 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.

下面我举个例子:

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;
它有效,但年龄被插入到对象中,名称和在第一种情况下插入名称并在插入年龄之后.

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 文档,所有 javascript 内容的绝佳来源.

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

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

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