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

Sử dụng Spread Syntax với Arguments trong JavaScript Functions


Spread operator cho phép tách (split) một array thành các argument đơn lẻ cho function.

Cú pháp

function myFunction(...iterableObj);

Ví dụ

<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)
      f = [...a, b, ...c, d];
      
      document.write(e);
      document.write("<br>" + f);
    </script>
  </body>
</html>

Ứng dụng thực tế: Gọi function với array arguments

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6 - spread array thành 3 arguments

// Math functions
console.log(Math.max(...[1, 5, 3, 9, 2])); // 9
console.log(Math.min(...[1, 5, 3, 9, 2])); // 1

// Constructor
const date = new Date(...[2024, 0, 15]); // Jan 15, 2024 (month 0-based)

Spread vs Apply (ES5)

// ES5 - dùng apply
function sum(x, y, z) { return x + y + z; }
const args = [1, 2, 3];
sum.apply(null, args); // 6

// ES6 - spread (clean hơn)
sum(...args); // 6

Lưu ý

  • Spread chỉ hoạt động với iterable (Array, String, arguments, NodeList...).
  • Trong function call, spread có thể dùng nhiều lần: fn(...arr1, ...arr2, val).
  • Performance: spread tạo array tạm, với array rất lớn có thể tốn memory. Dùng loop cho critical path.