[JavaScript] Rest/Spread Properties的顺序相关性

Rest/Spread Properties,目前是Stage 3的特性。
在使用Babel编译后,表现出了顺序相关性,如果多个被展开的对象具有同名属性,会产生冲突,后者覆盖前者。

1. 用于对象的属性中

const a = { x: 1 };
const b = { x: 2 };

const r1 = {...a,...b };
const r2 = {...b,...a };
console.warn(JSON.stringify(r1));    //{"x":2}
console.warn(JSON.stringify(r2));    //{"x":1}

2. 用于React组件的属性中

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

const a = { x: 1 };
const b = { x: 2 };

class A extends Component {
    render() {
        return (
            
ab{/* "x"=2 */} ba{/* "x"=1 */}
); } } ReactDOM.render( , document.getElementById('page') );

注:
(1)Rest/Spread Properties可用于获取剩余属性

const a = { x: 1, y: 3 };
const {x,...u} = a;

console.info(JSON.stringify(u));    //{"y":3}

(2)剩余属性可以为空

const a = { x: 1 };
const {x,...u} = a;

console.info(JSON.stringify(u));    //{}

(3)不能同时出现两个:Cannot have multiple rest elements when destructuring.

const a = { x: 1, y: 3 };
const {x,...u,...v} = a;

参考

Github:tc39/proposals
ecmascript-rest-spread

你可能感兴趣的:([JavaScript] Rest/Spread Properties的顺序相关性)