Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Rest Parameter và Spread Operator trong JavaScript


Rest Parameter (Tham số rest)

Cho phép đại diện nhiều argument thành một mảng (array). ES6 giới thiệu. Ký hiệu ... (ba chấm) đặt trước tên tham số.

Cú pháp & Ví dụ

<html>
  <body>
    <script>
      function addition(...numbers) {
        var res = 0;
        numbers.forEach(function(number) {
          res += number;
        });
        return res;
      }
      document.write(addition(3));           // 3
      document.write(addition(9,10,11,12,13)); // 55
    </script>
  </body>
</html>

...numbers gom tất cả arguments thành array numbers. Dùng được .forEach, .reduce, .map...

Spread Operator (Toán tử spread)

Cho phép trải (expand) iterable (array, string, object...) thành các element/argument đơn lẻ.

Cú pháp

function myFunction(...iterableObj);

Ví dụ với arguments

function multiply(x, y) {
  return x * y;
}
var myArgs = [50, 100];
console.log(multiply(...myArgs)); // 5000 - spread array thành 2 arguments

Ví dụ khác: Merge array, object

<html>
  <body>
    <script>
      var a = [10, 20];
      var b = "rank";
      var c = [30, "points"];
      var d = "run";
      
      // concat method (cũ)
      e = a.concat(b, c, d);
      
      // spread operator (ES6) - ngắn gọn, readable
      f = [...a, b, ...c, d];
      
      document.write(e);       // 10,20,rank,30,points,run
      document.write("<br>" + f); // 10,20,rank,30,points,run
    </script>
  </body>
</html>

Spread với Object (ES2018)

const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const merged = { ...obj1, ...obj2 }; // { a:1, b:2, c:3, d:4 }

// Clone object
const clone = { ...obj1 };

// Override property
const updated = { ...obj1, b: 20 }; // { a:1, b:20 }

Rest vs Spread - Tóm tắt

Đặc điểmRest Parameter (...params)Spread Operator (...arr)
Vị tríFunction parameter (định nghĩa)Function call / Array literal / Object literal
Hành độngThu gom (collect) nhiều thành 1 mảngTrải (expand) 1 mảng thành nhiều element
Ví dụfunction f(...args) {}f(...args), [...arr1, ...arr2]

Lưu ý

  • Rest parameter phải là tham số cuối cùng: function f(a, b, ...rest).
  • Chỉ có một rest parameter mỗi function.
  • Spread chỉ dùng trên iterable (Array, String, Map, Set, arguments, NodeList...).
  • Spread object chỉ copy shallow (nested object vẫn share reference).