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

การใช้ Arguments Object กับ Rest, Default และ Destructured Parameters ใน JavaScript

Default Parameters

Default Parameters ช่วยกำหนดค่าเริ่มต้นให้พารามิเตอร์ได้ง่ายขึ้น หากไม่ส่งค่าหรือส่ง undefined จะใช้ค่า Default

ตัวอย่าง

<html> 
  <body> 
    <script> 
      function inc(val1, inc = 1) { 
        return val1 + inc; 
      } 
      document.write(inc(10,10)); 
      document.write("<br>"); 
      document.write(inc(10)); 
    </script> 
  </body> 
</html>

Rest Parameters

ES6 นำ Rest Parameters มา ช่วยจัดการ Arguments Object ได้ง่ายขึ้น ใช้ ... นำหน้าพารามิเตอร์

ตัวอย่าง

<html> 
  <body> 
    <script> 
      function addition(...numbers) { 
        var res = 0; 
        numbers.forEach(function (number) { 
          res += number; 
        }); 
        return res; 
      } 
      document.write(addition(3)); 
      document.write(addition(5,6,7,8,9)); 
    </script> 
  </body> 
</html>

Destructuring

Destructuring ใน ES6 ใช้สำหรับ Binding ด้วย Pattern Matching หากไม่พบค่า จะคืน undefined

ตัวอย่าง

<html> 
  <body> 
    <script> 
      let marks = [92, 95, 85]; 
      let [val1, val2, val3] = marks; 
      document.write("Value 1: "+val1); 
      document.write("<br>Value 2: "+val2); 
      document.write("<br>Value 3: "+val3); 
    </script> 
  </body> 
</html>