我们使用
+
运算符将两个或多个数字相加。
示例 1: 将两个数字相加
const num1 = 5; const num2 = 3; // add two numbers const sum = num1 + num2; // display the sum console.log('The sum of ' + num1 + ' and ' + num2 + ' is: ' + sum);
输出
The sum of 5 and 3 is: 8
示例2: 将用户输入的两个数字相加
// store input numbers const num1 = parseInt(prompt('Enter the first number ')); const num2 = parseInt(prompt('Enter the second number ')); //add two numbers const sum = num1 + num2; // display the sum console.log(`The sum of ${num1} and ${num2} is ${sum}`);
输出
Enter the first number 5 Enter the second number 3 The sum of 5 and 3 is: 8
上述程序要求用户输入两个数字。在这里,
prompt()
用于接受用户的输入。
parseInt()
用于将用户输入的字符串转换为数字。
const num1 = parseInt(prompt('Enter the first number ')); const num2 = parseInt(prompt('Enter the second number '));
然后,计算数字之和。
const sum = num1 + num2;
最后显示总和。为了显示结果,我们使用了模板文字
` `
。这允许我们在字符串中包含变量。
console.log(`The sum of ${num1} and ${num2} is ${sum}`);
要在
``
中包含变量,您需要使用
${variable}
格式。
注意: 模板文字是在 ES6 中引入的,一些浏览器可能不支持它们。要了解更多信息,请访问 JavaScript 模板文字支持。