我们使用 +
运算符来对两个或多个数字进行相加。
示例 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 模板字面量 支持。