JavaScript中输入的数字如何相加?

How do I add numbers that have been inputted in JavaScript?

因此,我的代码允许用户输入 2 个数字,num1num2。但是,加法函数是连接数字而不是相加。请问我该如何解决这个问题?

这是函数的一个片段:

var sum= num1 + num2;
alert(`Sum of ${num1} and ${num2} is ${sum}`);

value 的类型为 string。这就是字符串连接发生的原因。要执行算术运算,您必须将值转换为数字。

改变

var sum= num1 + num2;

var sum= Number(num1) + Number(num2);

你需要将字符串转换为数字,+符号是连接字符串,这里是例子

var sum= Number(num1) + Number(num2);
alert(`Sum of ${num1} and ${num2} is ${sum}`); // Sum of 1 and 2 is 3

var sum= +num1 + +num2;
alert(`Sum of ${num1} and ${num2} is ${sum}`); // Sum of 1 and 2 is 3

这是因为即使输入类型是数字,值也是字符串形式,而不是添加它,它会在添加之前将 values.Convert 它们连接到数字

var sum = Number(num1) + Number(num2);
alert(`Sum of ${num1} and ${num2} is ${sum}`);

您可以强制将其串起来并使用 "" + num1 + num2

var sum = "" + num1 + num2;
alert('Sum of ${num1} and ${num2} is ${sum}');

另一个想法是使用 parseInt()

const sum = parseInt(num1) + parseInt(num2)
console.log(`Sum of ${num1} and ${num2} is ${sum}`)

这里是工作代码

let num1 = 50
let num2 = "5" //in case of string value the value will be converted by parseInt()
const sum = parseInt(num1) + parseInt(num2)
console.log(`Sum of ${num1} and ${num2} is ${sum}`)