ใช้ reduce() วิธีการใน JavaScript เพื่อใช้ฟังก์ชันพร้อมกันกับค่าสองค่าของอาร์เรย์จากซ้ายไปขวาเพื่อลดให้เป็นค่าเดียว
ต่อไปนี้คือพารามิเตอร์ -
- โทรกลับ − ฟังก์ชันที่จะดำเนินการกับแต่ละค่าในอาร์เรย์
- ค่าเริ่มต้น − Object ที่จะใช้เป็นอาร์กิวเมนต์แรกในการเรียก callback ครั้งแรก
ตัวอย่าง
คุณสามารถลองเรียกใช้โค้ดต่อไปนี้เพื่อเรียนรู้วิธีทำงานโดยใช้วิธี reduce() ใน JavaScript -
<html>
<head>
<title>JavaScript Array reduce Method</title>
</head>
<body>
<script>
if (!Array.prototype.reduce) {
Array.prototype.reduce = function(fun /*, initial*/) {
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
// no value to return if no initial value and an empty array
if (len == 0 && arguments.length == 1)
throw new TypeError();
var i = 0;
if (arguments.length >= 2) {
var rv = arguments[1];
} else {
do {
if (i in this) {
rv = this[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= len)
throw new TypeError();
}
while (true);
}
for (; i < len; i++) {
if (i in this)
rv = fun.call(null, rv, this[i], i, this);
}
return rv;
};
}
var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; });
document.write("total is : " + total );
</script>
</body>
</html>