美文网首页JavaScript
[JavaScript] Rest/Spread Propert

[JavaScript] Rest/Spread Propert

作者: 何幻 | 来源:发表于2017-01-03 22:58 被阅读9次

    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

    相关文章

      网友评论

        本文标题:[JavaScript] Rest/Spread Propert

        本文链接:https://www.haomeiwen.com/subject/czonvttx.html