在 JavaScript 中相加两个数字
在本文中,我们将学习和使用 JavaScript 源代码中的算术运算,以及如何获取多个数值的总和,并使用默认的警报框和日志框将结果显示给用户。
在 JavaScript 中相加数字
为了找出算术运算的结果,例如(加法、减法、乘法和除法),我们在 JavaScript 代码语句中使用运算符。开发人员大多使用这些运算符在他们的程序中执行计算和进一步的数学问题。
为了找到加法,程序员使用带有数值的+
运算符。
JavaScript 中的加法 (+
) 运算符
在 JavaScript 中,+
运算符获取数值的总和结果。如果我们在字符串值中使用+
运算符,它将在字符串之间执行连接。
语法:
let value1 = 10
let value2 = 5
let sum = value1 + value2 // addition of values
console.log(sum);
我们需要分配多个数字值或用户提供的值来执行加法运算。在下面的示例中,我们将从用户输入中获取两个值并执行加法运算,然后将结果显示给用户。
示例代码:
<html>
<head>
<title> display JavaScript alert </title>
</head>
<script>
function createSum()
{
let data1 = document.getElementById("value1").value;
data1 = parseInt(data1)
let data2 = document.getElementById("value2").value;
data2 = parseInt(data2)
if(isNaN(data1) || isNaN(data2)) //check empty data field
{
alert("Please enter both values");
}else{
let sum = data1+data2;
alert("Your'e sum value is : "+sum);
}
}
</script>
<body>
<h1 style="color:blueviolet">DelftStack Learning</h1>
<h3>JavaScript Add two values</h3>
<form onsubmit ="return createSum()">
<!-- data input -->
<td> Enter 1st Value: </td>
<input id = "value1" type="number">
<td> Enter 2nd Value: </td>
<input id = "value2" type="number">
<br><br>
<input type = "submit" value = "Sum values">
</form>
</body>
</html>
输出:
我们使用上述 HTML 源代码中的表单元素来创建用户输入字段和提交按钮。用户将插入这两个值,当用户单击提交按钮时,函数 createSum()
将触发。
在脚本标签中,我们声明了 createSum()
函数,在该函数中,我们在 data1
和 data2
变量中获取用户输入值,并使用条件语句 if
来检查输入值。
如果值为空或不包含数字,则会显示错误消息 alert()
。如果用户提供了两个数值,那么在 else
条件下,我们使用 +
运算符执行加法,将结果存储在 sum
变量中,并将其显示在 alert()
弹出窗口中。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。