JavaScript รองรับตัวดำเนินการเลขคณิตต่อไปนี้ สมมติว่าตัวแปร A มีค่า 10 และตัวแปร B มีค่าเท่ากับ 20 จากนั้น -
| Sr.No | ตัวดำเนินการและคำอธิบาย |
|---|---|
| 1 | + (เพิ่มเติม) เพิ่มตัวถูกดำเนินการสองตัว เช่น: A + B จะให้30 |
| 2 | - (การลบ) ลบตัวถูกดำเนินการที่สองออกจากตัวแรก เช่น: A - B จะให้ -10 |
| 3 | * (การคูณ) คูณทั้งสองตัวถูกดำเนินการ เช่น: A * B จะให้ 200 |
| 4 | / (ดิวิชั่น) หารตัวเศษด้วยตัวส่วน เช่น: B / A จะให้2 |
| 5 | % (โมดูลัส) แสดงผลส่วนที่เหลือของการหารจำนวนเต็ม เช่น: B % A จะให้ 0 |
| 6 | ++ (เพิ่มขึ้น) เพิ่มค่าจำนวนเต็มหนึ่ง เช่น: A++ จะให้ 11 |
| 7 | -- (ลดลง) ลดค่าจำนวนเต็มลงหนึ่ง เช่น: A-- จะให้ 9 |
โค้ดต่อไปนี้แสดงวิธีใช้ตัวดำเนินการเลขคณิตใน JavaScript
ตัวอย่าง
การสาธิตสด
<html>
<body>
<script>
<!--
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);
a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);
b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
</script>
Set the variables to different values and then try...
</body>
</html>