天天看點

學習之es6運算符...學習之es6運算符…

學習之es6運算符…

1.擴充運算符(spread)-----------應用

将一個數組轉為用逗号分離的序列

const a = ['xxx','hhh','yyy'];
console.log('1',...a,'1')// 1 xxx hhh yyy 1
// 即...a 為 'xxx','hhh','yyy'
           
  • 作為函數調用的參數

function add(x, y) {
  return x + y;
}
const numbers = [4, 38];
console.log(add(...numbers)) // 42
           
  • 替代函數的 apply 方法

Math.max(14, 3, 77, 11);// max函數需要傳入多個參數
//當參數在一個數組裡面時,使用aplly方法,傳入數組參數
Math.max.apply(null, [14, 3, 77, 11])
// 有了...運算符,不用使用apply方法了
Math.max(...[14, 3, 77])
           
  • 複制數組

const a1 = [1, 2];
const a2 = [...a1];// 寫法一,得到的是一個新的數組并不是複制了指針位址
const [...a3] = a1;// 寫法二,與寫法一得到的結果一樣,相當于...a3建立了一個新的數組,并把a1裡的值給了a3新建立的數組
console.log(a1)// [ 1, 2 ]
console.log(a2)// [ 1, 2 ]
console.log(a3)// [ 1, 2 ]
           
  • 合并數組

const arr1 = ['a', 'b'];
const arr2 = ['c'];
const arr3 = ['d', 'e'];
const arr4 = [...arr1, ...arr2, ...arr3]
console.log(arr4)// [ 'a', 'b', 'c', 'd', 'e' ]
           
  • 與解構指派結合

const [first, ...rest] = [1, 2, 3, 4, 5];
first // 1
rest  // [2, 3, 4, 5]跟複制數組的第二種寫法類似
           
  • 字元串

2.rest 參數(…變量名)

用于擷取函數的多餘參數

function add1(x,y,...values) {
  console.log(values) // [ 5, 10 ]
  return x+y
}
console.log(add1(2,4,5,10))// 6