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

การใช้งาน Higher-Order Functions ใน JavaScript

Higher-order functions เป็นฟังก์ชันที่รับฟังก์ชันอื่นเป็นอาร์กิวเมนต์ หรือคืนค่าฟังก์ชัน ช่วยลดโค้ด เพิ่มความอ่านง่าย ตัวอย่างเช่น map, filter, reduce

ตัวอย่าง ไม่ใช้ Higher-order function (ใช้ for loop)

<html> <body> <script> 
    const name = []; 
    var persons = [ 
        { name: 'Frodobaggins'}, 
        { name: 'aragorn'}, 
        { name: 'gandalf'}, 
        { name: 'pippin'}, 
        { name: 'nazgul'} 
    ]; 
    for(let i = 0; i < persons.length; i++) { 
        if(persons[i].name.length > 6) { 
            name.push(persons[i]); 
        } 
    } 
    document.write(JSON.stringify(name)); 
</script> </body> </html>

ผลลัพธ์

[{"name":"Frodobaggins"},{"name":"aragorn"},{"name":"gandalf"}]

ตัวอย่าง ใช้ filter() (Higher-order function)

<html> <body> <script> 
    const persons = [ 
        { name: 'Frodobaggins'}, 
        { name: 'aragorn'}, 
        { name: 'gandalf'}, 
        { name: 'pippin'}, 
        { name: 'nazgul'} 
    ]; 
    const name = persons.filter(person => person.name.length > 7); 
    document.write(JSON.stringify(name)); 
</script> </body> </html>

ผลลัพธ์

[{"name":"Frodobaggins"}]

โค้ดสั้นกว่า อ่านง่ายกว่า ไม่ต้องสร้างอาร์เรย์ใหม่และ for loop เอง