1. 程式人生 > >ES6(...)展開運算子

ES6(...)展開運算子

函式傳參

展開運算子可以展開陣列,所以不再需要apply方法,將陣列轉為函式的引數了

                 // ES5 的寫法
                 function f(x, y, z) {
                 // ...
                 }
                 var args = [0, 1, 2];
                 f.apply(null, args);
                 // ES6 的寫法
                 function f(x, y, z) {
                 // ...
                 }
                 var args = [0, 1, 2];
                 f(...args);

資料解構

其實就是把陣列的每個資料拆開然後放進去

                let arr = ['autumn', 'wscats'];
		// 析構陣列
		let y;
		[autumn, ...y] = arr;
		console.log(y) // ["wscats"]

資料構造

兩個物件連線返回新的物件

               let x = {
			name: 'autumn'
		}
		let y = {
			age: 18
		}
		let z = {...x,...y}
		console.log(z)

兩個陣列連線返回新的陣列

                let x = ['autumn']
		let y = ['wscats']
		let z = [...x, ...y]
		console.log(z)// ["autumn", "wscats"]

陣列加上物件返回新的陣列

                let x = [{
			name: 'autumn'
		}]
		let y = {
			name: 'wscats'
		}
		let z = [...x, y];
		console.log(z);

image

陣列+字串

                let x = ['autumn'];
		let y = 'wscats';
		let z = [...x, y];
		console.log(z);

陣列+物件

               let x = {
			name: ['autumn','wscats'],
			age:18
		}
		let y = {
			...x,//name: ['autumn','wscats'],age:18
			arr: [...x.name]//['autumn','wscats']
			
		}
		console.log(y)