javascript(ES6)擴展運算子 Spread Operator

讀出第一層數據

1
2
3
4
const number=["1","2","3"];
let names = [...number];
console.log(names)
//(3) ['1', '2', '3']
1
2
3
4
const data={name:'lara',age:3};
let newdata = { ...data };
console.log(newdata)
//{name: 'lara', age: 3}

合併:等同於concat

1
2
3
4
5
var number1=[1,2,3];
var number2=[4,5,6];
let newnumber = [...number1,...number2];
console.log(newnumber)
//(6) [1, 2, 3, 4, 5, 6]

合併复制数组或对象内部数据:等同於concat

1
2
3
4
5
6
7
8
9
10
var data1={name:'Test'};
var data2={age:5};
let newData3 = {...data1,...data2};
console.log(newData3)
//{name: 'Test', age: 5}

const parts = ['shoulders', 'knees'];
const lyrics = ['head', ...parts, 'and', 'toes'];
console.log(lyrics)
(5) ['head', 'shoulders', 'knees', 'and', 'toes']

字符串轉字符数组 =>類似于 split() 方法

1
2
3
4
5
6
7
8
var one='Hello Word';
var array1 =[...one]
console.log('字符串轉字符数组',array1)
//(10) ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'd']

let text = [...'Hello'];
console.log(text);
//(5) ['H', 'e', 'l', 'l', 'o']

當你有一個接受數字的函數,並且你將這些數字作為數組的元素時,以前的实现是使用 apply()相同

1
2
3
4
5
6
let scores = [12, 33, 6]
const addAll = (a, b, c) => {
console.log(a + b + c);
};
addAll(...scores);
//51

使用在陣列的 push 方法上

1
2
3
4
let list = [1, 2];
list.push(...[3, 4]);
console.log(list)
//(4) [1, 2, 3, 4]