📖
JavaScript - 網站程式設計
  • JavaScript - 網站程式設計
  • 1. 簡介
    • 1.1 講者簡介
    • 1.2 課程簡介
    • 1.3 開發工具簡介
  • 2. JS 在網頁上的基本觀念
    • 2.1 變數宣告
    • 2.2 資料型態
    • 2.3 基礎節點操控
    • 2.4 套用方式
  • 3. 瀏覽器物件模型 (BOM)
    • 3.1 Window
    • 3.2 Location
    • 3.3 內建彈出視窗
  • 4. 文件物件模型 (DOM)
    • 4.1 DOM 簡介
    • 4.2 取得節點、內容、屬性
    • 4.3 節點查找(Traversing)
    • 4.4 更新節點
    • 4.5 新增節點
    • 4.6 刪除節點、屬性
    • 4.7 操控 class 屬性
    • 4.8 練習
  • 5. 事件 (Events)
    • 5.1 事件(Event)簡介
    • 5.2 事件物件(Event Object)
    • 5.3 window 及 document 事件
    • 5.4 滑鼠相關事件
    • 5.5 鍵盤相關事件
    • 5.6 scroll 事件
    • 5.7 表單事件及停止元素預設行為
    • 5.8 動態事件綁定
    • 5.9 練習
  • 6. 表單 (Form)
    • 6.1 取得表單資料
    • 6.2 設定表單資料
    • 6.3 練習
  • 7. 儲存機制(Storage)
    • 7.1 Cookies
    • 7.2 localStorage
  • 8. ECMAScript (ES)
    • 8.1 Template String
    • 8.2 Arrow Function
    • 8.3 Spread and Rest Operator
    • 8.4 物件屬性簡寫
    • 8.5 解構賦值
  • 9. 作業
  • 10. 參考資料
Powered by GitBook
On this page
  • Spread 運算子(...)
  • Rest 運算子(...)
  1. 8. ECMAScript (ES)

8.3 Spread and Rest Operator

Spread Operator(展開運算子)、Rest Operator(其餘運算子)。這兩個運算子,符號都是一樣的,即 ...。

Spread 運算子(...)

以陣列為例:

var a = [1, 2, 3];
var b = [4, ...a, 5];
console.log(a); // [1, 2, 3]
console.log(b); // [4, 1, 2, 3, 5]

以物件為例:

var c = {
  a: 1,
  b: 2
};
var d = {
  b: 3,
  ...c,
  f: 6
};

console.log(c); // {a: 1, b: 2}
console.log(d); // {a: 1, b: 2, f: 6}

改成以下:

var c = {
  a: 1,
  b: 2
};
var d = {
  ...c,
  b: 3,
  f: 6
};

console.log(c); // {a: 1, b: 2}
console.log(d); // {a: 1, b: 3, f: 6}

範例:

Rest 運算子(...)

參數傳遞至函式中時,不確定傳過來的參數有幾個,那就用 ... 這語法,再加上一個自訂的變數名稱,例如範例1的 ...others:此時在函式中,就可以使用 others 這個陣列來取得參數:

範例 1:

function add(...others){
  console.log(others); // [1, 2, 3, 4, 5]
  let total = 0;
  for(let i = 0; i < others.length; i++){
    total += others[i];
  }
  return total;
}

let result = add(1, 2, 3, 4, 5);
console.log(result); // 15

範例 2:

延續上例,測試看看這個:

/* Rest Operator:用在函式 */
function add(a, b, ...others){
  console.log(a); // 1
  console.log(b); // 2
  console.log(others); // [3, 4, 5]
  let total = 0;
  for(let i = 0; i < others.length; i++){
    total += others[i];
  }
  return total;
}

let result = add(1, 2, 3, 4, 5);
console.log(result); // 12

Rest Operator 參數一定要放在最後。

Previous8.2 Arrow FunctionNext8.4 物件屬性簡寫

Last updated 1 year ago