es6新特性中...的用法


1.展開運算符

能夠將對象字面量展開為多個元素

const books = ["Don Quixote", "The Hobbit", "Alice in Wonderland", "Tale of Two Cities"];
console.log(...books);

輸出:Don Quixote The Hobbit Alice in Wonderland Tale of Two Cities

還可以將數組結合

沒有...之前,使用的是concat

const fruits = ["apples", "bananas", "pears"];
const vegetables = ["corn", "potatoes", "carrots"];
const produce = fruits.concat(vegetables);
console.log(produce);

 輸出:["apples", "bananas", "pears", "corn", "potatoes", "carrots"]

使用...之后

const fruits = ["apples", "bananas", "pears"];
const vegetables = ["corn", "potatoes", "carrots"];
const produce = [...fruits,...vegetables];
console.log(produce);

  輸出結果一樣

2.剩余參數

可以將剩余不定數的參數保存到一個數組中

const order = [20.17, 18.67, 1.50, "cheese", "eggs", "milk", "bread"];
const [total, subtotal, tax, ...items] = order;
console.log(total, subtotal, tax, items);

  輸出:20.17, 18.67, 1.50,["cheese", "eggs", "milk", "bread"]

3.代替argumens

對於參數不固定的函數,es6之前的處理方法是使用arguments,

function sum() {
  let total = 0;  
  for(const argument of arguments) {
    total += argument;
  }
  return total;
}

  而現在直接使用剩余參數運算符就可以

function sum(...nums){
  let total = 0;
  for(const num of nums ){
      total += num; 
   }
  return total;  
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM