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

การส่ง Arguments จำนวนไม่ทราบให้ Function ใน JavaScript

เมื่อเรียก Function ใน JavaScript ส่ง Arguments กี่ตัวก็ได้ ไม่มี Limit ของ Function Parameters นั่นหมายถึง Functions ไม่สามารถ Overload แบบดั้งเดิมใน JS ได้

Arguments Object เป็น Local Variable พร้อมใช้ใน Non-arrow Functions ทุกตัว สามารถอ้างอิง Arguments ของ Function ภายใน Function ได้ด้วย Arguments Object มี Entry สำหรับแต่ละ Argument ที่เรียก Function พร้อม Index 0 เริ่มต้น

เช่น ถ้า Function ถูกส่ง 3 Arguments เข้าถึงได้ดังนี้

arguments[0] // first argument arguments[1] // second argument arguments[2] // third argument

Note - Arguments เป็น Array-like Object เข้าถึงได้ใน Functions มี Values ของ Arguments ที่ส่งมา "Array-like" หมายถึงมี Length Property และ Properties Indexed from Zero แต่ไม่มี Built-in Methods ของ Array เช่น forEach() และ map()

เช่น เพื่อรับ Arbitrary Number ของ Args สร้าง Function ได้ดังนี้

ตัวอย่าง

function printAllArguments(a, b) {    console.log("First arg: " + a)    console.log("Second arg: " + b)    console.log("All args: " + arguments) } printAllArguments(1) printAllArguments(1, "hello") printAllArguments(1, "hello", 1, "hello")

ผลลัพธ์

First arg: 1 Second arg: undefined All args: {"0":1} First arg: 1 Second arg: hello All args: {"0":1,"1":"hello"} First arg: 1 Second arg: hello All args: {"0":1,"1":"hello","2":1,"3":"hello"}