JavaScript Array mengurangi ()
Contoh
Kurangi semua angka dalam array:
const numbers = [175, 50, 25];
document.getElementById("demo").innerHTML
= numbers.reduce(myFunc);
function myFunc(total, num) {
return total - num;
}
Bulatkan semua angka dan tampilkan jumlahnya:
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);
}
Definisi dan Penggunaan
Metode reduce()
mengeksekusi fungsi peredam untuk elemen array.
Metode reduce()
mengembalikan nilai tunggal: hasil akumulasi fungsi.
Metode reduce()
tidak menjalankan fungsi untuk elemen array kosong.
Metode reduce()
ini tidak mengubah larik asli.
Lihat juga:
Sintaksis
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Parameter
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. |
Nilai Kembali
Hasil akumulasi dari panggilan terakhir dari fungsi panggilan balik. |
Dukungan Peramban
reduce()
adalah fitur ECMAScript5 (ES5).
ES5 (JavaScript 2009) didukung penuh di semua browser:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |