JavaScript Array ลด ()
ตัวอย่าง
ลบตัวเลขทั้งหมดในอาร์เรย์:
const numbers = [175, 50, 25];
document.getElementById("demo").innerHTML
= numbers.reduce(myFunc);
function myFunc(total, num) {
return total - num;
}
ปัดเศษตัวเลขทั้งหมดและแสดงผลรวม:
const numbers = [15.5, 2.3, 1.1, 4.7];
document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0);
function getSum(total, num) {
return total + Math.round(num);
}
ความหมายและการใช้งาน
วิธี การreduce()
ดำเนินการฟังก์ชันลดสำหรับองค์ประกอบอาร์เรย์
วิธี การreduce()
คืนค่าเดียว: ผลลัพธ์สะสมของฟังก์ชัน
เมธอด นี้reduce()
ไม่เรียกใช้ฟังก์ชันสำหรับอิลิเมนต์อาร์เรย์ว่าง
วิธี การreduce()
นี้จะไม่เปลี่ยนอาร์เรย์เดิม
ดูสิ่งนี้ด้วย:
ไวยากรณ์
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
พารามิเตอร์
Parameter | Description | ||||||||
function() | Required. A function to be run for each element in the array. |
||||||||
Reducer function parameters:
| |||||||||
initialValue | Optional. A value to be passed to the function as the initial value. |
คืนมูลค่า
ผลสะสมจากการเรียกฟังก์ชันโทรกลับครั้งสุดท้าย |
รองรับเบราว์เซอร์
reduce()
เป็นคุณลักษณะ ECMAScript5 (ES5)
ES5 (JavaScript 2009) รองรับทุกเบราว์เซอร์:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |