Saturday, November 19, 2016

JavaScript Array reduce() Method

array.reduce(function(total,currentValue,currentIndex,arr),initialValue)
Returns the accumulated result from the last call of the callback function

<button onclick="myFunction()">Try it</button>
<p>Sum of numbers in array: <span id="demo"></span></p>
<script>
var numbers = [15.5, 2.3, 1.1, 4.7];
function getSum(total, num) {
    return total + Math.round(num);
}
function myFunction(item) {
    document.getElementById("demo").innerHTML = numbers.reduce(getSum,0);
}
</script>

http://www.w3schools.com/jsref/jsref_reduce.asp
http://www.tuicool.com/articles/6ziqmu2

No comments:

Post a Comment