JavaScript 算术运算符

JavaScript 算术运算符包括加法、减法、乘法、除法和模运算符等。所有这些运算符都是二元运算符,这意味着它们作用于两个操作数。下表显示了带有示例的算术运算符。

算术运算符运算示例
+加法10 + 2 = 12
减法10 – 2 = 8
*乘法10 * 2 = 20
/除法10 / 2 = 5
%取模 – 返回除法运算后的余数10 % 2 = 0 (此处余数为零)。如果为 10 % 3,则结果为 1。

JavaScript 算术运算符示例

在此算术运算符示例中,我们使用了两个变量 a 和 b,它们的值分别为 12 和 3。我们将使用这两个变量来执行各种算术运算。

<!DOCTYPE html>
<html>
<head>
    <title>JavascriptArithmeticOperators </title>
</head>
<body>
    <h1>PerformingArithmeticOperations </h1>
<script>
   var a = 12, b = 3;
   var addition, subtraction, multiplication, division, modulus;

   addition = a + b; //addition of 3 and 12
   subtraction = a - b; //subtract 3 from 12
   multiplication = a * b; //Multiplying both
   division = a / b; //dividing 12 by 3 (number of times)
   modulus = a % b; //calculation the remainder

   document.write("Addition of " +a +' and ' +b +" is = " + addition + "<br />");
   document.write("Subtraction of " +a +' and ' +b +" is = " + subtraction + "<br />");
   document.write("Multiplication of " +a +' and ' +b +" is = " + multiplication + "<br />");
   document.write("Division of " +a +' and ' +b +" is = " + division + "<br />");
   document.write("Modulus of " +a +' and ' +b +" is = " + modulus + "<br />");
</script>
</body>
</html>
Performing Arithmetic Operations
Addition of 12 and 3 is = 15
Subtraction of 12 and 3 is = 9
Multiplication of 12 and 3 is = 36
Division of 12 and 3 is = 4
Modulus of 12 and 3 is = 0

算术运算符示例 2

在此 JavaScript 示例中,我们也使用了两个变量 a 和 b,它们的值分别为 12 和 3。在这里,我们将使用这些变量向您展示如何将算术运算的输出显示在段落中。

<!DOCTYPE html>
<html>
<head>
    <title>JavascriptArithmeticOperators 2</title>
</head>
<body>
    <h1>Performing Arithmetic Operations </h1>
    <p id = 'add'> Addition </p>
    <p id = 'sub'> Subtraction </p>
    <p id = 'mul'> Multiplication </p>
    <p id = 'div'> Division </p>
    <p id = 'mod'> Modulus </p>
<script>
   var a = 12, b = 3;
   var add, sub, mul, div, mod;

   add = a+b; //addition of 3 and 12
   sub = a-b; //subtract 3 from 12
   mul = a*b; //Multiplying both
   div = a/b; //dividing 12 by 3 (number of times)
   mod = a%b; //calculation the remainder

   document.getElementById("add").innerHTML = "Addition of " +a +' and ' +b +" is = " + add;
   document.getElementById("sub").innerHTML = "Subtraction of " +a +' and ' +b +" is = " + sub;
   document.getElementById("mul").innerHTML = "Multiplication of " +a +' and ' +b +" is = "+ mul;
   document.getElementById("div").innerHTML = "Division of " +a +' and ' +b +" is = " +  div;
   document.getElementById("mod").innerHTML = "Modulus of " +a +' and ' +b +" is = " +  mod;
</script>
</body>
</html>
Arithmetic Operators 2