[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 (
            <div>
                <span {...a} {...b}>ab</span>{/* "x"=2 */}
                <span {...b} {...a}>ba</span>{/* "x"=1 */}
            </div>
        );
    }
}

ReactDOM.render(
    <A />,
    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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容