ES6 展開語法(Spread syntax)

原文鏈接:https://zhidao.baidu.com/question/2273108742043762308.html

展開語法,屬於es6的新語法,可以在函數調用、數組構造、構造字面量對象時, 將數據展開賦值。

1、函數調用,展開數組參數

function sum(x, y, z) {
  return x + y + z;
}
const numbers = [1, 2, 3];
sum(...numbers);

2、構造數組,展開數組

const arr1 = [3,4,5];
const arr2 = [0, 1, 2, ...arr1];    // [0,1,2,3,4,5]

3、構造數組,展開字符串

const str = 'abc';
const arr = [...str];    // ['a', 'b', 'c']

 

4、構造對象,展開對象

const obj1 = {a: 1, b: 2, c: 3};
const obj2 = {...obj1, d: 4};    // {a: 1, b: 2, c: 3, d: 4}
const obj3 = {...obj1, c: 4};    // {a: 1, b: 2, c: 4}
const obj4 = {c: 4, ...obj1};    // {a: 1, b: 2, c: 3}

5、JSX組件屬性展開

render(){
    const settings = {
        value: 1,
        placeholder: '輸入數值'
    };
    return <MyInput {...settings}/>
    // 上面的寫法類似於
    // return <MyInput 
    //             value={settings.value} 
    //             placeholder={settings.placeholder}/>
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章