展開語法,屬於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}/>
}