JavaScript hỗ trợ các toán tử số học sau. Giả sử biến A giữ 10 và biến B giữ 20, sau đó -
| Sr.No | Toán tử và Mô tả |
|---|---|
| 1 | + (Bổ sung) Thêm hai toán hạng Ví dụ: A + B sẽ cho 30 |
| 2 | - (Phép trừ) Trừ toán hạng thứ hai với toán hạng đầu tiên Ví dụ: A - B sẽ cho -10 |
| 3 | * (Phép nhân) Nhân cả hai toán hạng Ví dụ: A * B sẽ cho 200 |
| 4 | / (Phân chia) Chia tử số cho mẫu số Ví dụ: B / A sẽ cho 2 |
| 5 | % (Mô-đun) Kết quả còn lại của một phép chia số nguyên Ví dụ: B% A sẽ cho 0 |
| 6 | ++ (Phần tăng dần) Tăng một giá trị số nguyên lên một Ví dụ: A ++ sẽ cho 11 |
| 7 | - (Giảm) Giảm một giá trị số nguyên Ví dụ: A-- sẽ cho 9 |
Đoạn mã sau trình bày cách sử dụng các toán tử số học trong JavaScript.
Ví dụ
Bản trình diễn trực tiếp
<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>