ตัวดำเนินการทางคณิตศาสตร์พื้นฐานใน JavaScript มีดังต่อไปนี้ -
- ตัวดำเนินการเลขคณิต
- ตัวดำเนินการเปรียบเทียบ
- ตัวดำเนินการเชิงตรรกะ (หรือเชิงสัมพันธ์)
- ผู้ดำเนินการมอบหมาย
เรามาดูกันว่าตัวดำเนินการเลขคณิตทำงานอย่างไรและมีอะไรบ้าง -
| 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 = 77;
var b = 30;
var c = "Demo";
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>
</body>
</html>