Home > Article > Web Front-end > jquery sum function
First of all, jQuery is a library written in JavaScript. It contains many convenient and fast tool functions to facilitate front-end developers to implement page interaction and dynamic effects. This includes functions that implement the summation function.
In the jQuery library, there are many functions that implement the summation function. You can choose the appropriate function to call according to your own business needs. The following are several commonly used jQuery sum functions.
Theeach function is a commonly used iteration function in jQuery. It can traverse an array or object and operate on each element. Each element in the array can be added together to get the sum of all elements by executing a callback function on each element.
Sample code:
var sum = 0;
$.each([2,4,6,8], function(index, value){
sum += value;
});
console.log(sum); //20
map function is in jQuery Another commonly used iteration function is similar to the each function, but it returns a new array. We can use the map function to add each element in the original array and return a new array to achieve the summation effect.
Sample code:
var arr = [2, 4, 6, 8];
var sum = $.map(arr, function(num) {
return num;
}).reduce(function(total, num) {
return total + num;
});
console.log(sum); //20
The reduce function is a method in the JavaScript standard library and is also implemented in jQuery. This method iterates through each element of the array, accumulates it to a value, and finally gets the sum of these data.
Sample code:
var arr = [2, 4, 6, 8];
var sum = $.reduce(arr, function(total, num) {
return total + num;
}, 0);
console.log(sum); //20
If we don't want to use the functions in the jQuery library, we can also write a summation function ourselves. Below is a custom function called getArraySum that adds the elements in an array containing numbers and returns the sum.
Sample code:
function getArraySum(array){
var sum = 0; for(var i=0; i<array.length; i++){ sum += parseInt(array[i]); } return sum;
}
var arr = [2, 4, 6, 8];
var sum = getArraySum(arr);
console.log(sum); //20
No matter which method is used, the jQuery sum function can make our development Work is easier and more efficient. It should be noted that when using these functions, you need to pay attention to the type and value range of the elements in the array to avoid problems caused by non-numeric types or numbers outside the range.
The above is the detailed content of jquery sum function. For more information, please follow other related articles on the PHP Chinese website!