Given an array [1, 2, 3, 4]
, how can I find the sum of its elements? (In this case, the sum would be 10
.)
I thought $.each might be useful,
When the array consists of strings one has to alter the code. This can be the case, if the array is a result from a databank request. This code works:
alert(
["1", "2", "3", "4"].reduce((a, b) => Number(a) + Number(b), 0)
);
Here, ["1", "2", "3", "4"] ist the string array and the function Number()
converts the strings to numbers.