Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีใช้ Spread Syntax กับ Arguments ใน JavaScript Functions

Spread operator อนุญาตให้แยก array เป็น arguments เดี่ยวๆ ซึ่งเป็นฟังก์ชันของ arguments แยกกัน

Syntax

function myfunction(...iterableObj);

ตัวอย่าง

Live Demo

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

กรณีใช้งานทั่วไป (Use Cases)

// 1. เรียกฟังก์ชันด้วย array เป็น arguments
function sum(x, y, z) { return x + y + z; }
const numbers = [1, 2, 3];
sum(...numbers);  // 6 - เทียบเท่า sum(1, 2, 3)

// 2. ใช้กับ Math functions
Math.max(...[1, 5, 3, 9, 2]);  // 9
Math.min(...[1, 5, 3, 9, 2]);  // 1

// 3. Constructor with array
const date = new Date(...[2024, 0, 1]);  // 2024-01-01

// 4. Combine with rest parameters
function collect(first, ...rest) {
  console.log(first);  // 1
  console.log(rest);   // [2, 3, 4]
}
collect(...[1, 2, 3, 4]);