I have to write 6 small JavaScript scripts for school and I've got them all working apart from this one.
function calculate() {
var numbers = [
document.getElementById("num_one").value ,
document.getElementById("num_two").value ,
document.getElementById("num_three").value
];
var sum = numbers[0] + numbers[1] + numbers[2];
document.getElementById("display_sum").innerHTML = sum;
}
The user is supposed to enter 3 numbers click a button and it should add them all togther or "find the sum".
My Problem is, it just joins the numbers togther instead of adding them. Does anyone know a way to fix this?
Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.
To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.
You are "summing" string variables so Javascript is concatenating them.
You need to convert them to numbers in order to have an arithmetic sum:
function calculate() {
var numbers = [
document.getElementById("num_one").value ,
document.getElementById("num_two").value ,
document.getElementById("num_three").value
];
var sum = Number(numbers[0]) + Number(numbers[1]) + Number(numbers[2]);
document.getElementById("display_sum").innerHTML = sum;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With