ES6 三个点新语法:数组元素的 rest / spread ,与对象属性的 rest / spread

文章目录

    今天在看微信小程序 zanui 的 field 组件代码时,发现一个新的语法,即三个点:

    <template
          is="zan-field"
          data="{{ ...config.base.name, value }}"></template>
    

    其中的 config.base.name 是个对象,类似于

    name: {
    	focus: true,
    	title: '收货人',
    	placeholder: '名字'
    }
    

    如果不加这三个点就会报错

     Bad attr `data` with message
    <template
    	is="zan-field"
    > 11 |       data="{{ config.base.name }}"></template>
    

    第一次见此写法,查了一下才发现是 ES6 的新语法:Object rest and spread properties

    需要注意的是对象的 rest / spread 属性只在 V8 v6.0.75+ 和 Chrome 60+ 版本以上才支持。

    数组 rest elements 示例

    const numbers = [1, 2, 3, 4];
    => undefined
    const [a, ...b] = numbers;
    => undefined
    a
    => 1
    b
    => [ 2, 3, 4 ]
    

    数组 spread elements 示例

    const new_numbers = [a, ...b];
    => undefined
    new_numbers
    => [ 1, 2, 3, 4 ]
    

    对象的 rest properties 示例

    const person = { 
    ..     firstName: 'Zhongwei', 
    ..     lastName: 'Sun', 
    ..     country: 'China', 
    ..     state: 'Shandong', 
    .. };
    => undefined
    const { firstName, lastName, ...rest } = person;
    => undefined
    firstName
    => 'Zhongwei'
    rest
    => { country: 'China', state: 'Shandong' }
    

    对象的 spread properties 示例

    const new_person = { firstName, lastName, ...rest };
    => undefined
    new_person
    => { firstName: 'Zhongwei',
      lastName: 'Sun',
      country: 'China',
      state: 'Shandong' }
    

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式