0

Help with getting sum of array

Hi there I want to calculate the sum of an array from an input element. So, what is wrong with this code? let items = []; function total() { pricevalue = document.getElementById('price').value; items.push(pricevalue); let sum = 0; for (let i = 0; i < items.length; i++) { sum += items[i] + pricevalue; } document.getElementById("total").innerHTML = sum; } https://code.sololearn.com/WwNoyJ0BM1XF/?ref=app

9th Jul 2021, 7:57 PM
Talal Emran
Talal Emran - avatar
4 Réponses
+ 3
Fun (for me and some :P) fact: when you grab a value from an element, it is as a string. That is why, you will need to use the parseInt() method on either the declaration of the variable pricevalue ("pricevalue = parseInt(...);") or when pushing to the items array (items.push(parseInt(...);). The result will add the numbers mathematically instead of performing concatenation.
9th Jul 2021, 8:55 PM
HydroShock
HydroShock - avatar
0
Looks right to me except i don't understand the point of adding pricevalue two times . Is there any error you are receiving ?
9th Jul 2021, 8:27 PM
Abhay
Abhay - avatar
0
I have attached the project.
9th Jul 2021, 8:32 PM
Talal Emran
Talal Emran - avatar
0
that's not a "fun fact"... that's the way of values of elements (and quite all properties except such as 'checked' wich are boolean) are handled in html: as string (in same ways as you get input in any language, until you have some specific method wich handle for you the cast to another types)
9th Jul 2021, 9:42 PM
visph
visph - avatar