歡迎來到學習 JavaScript 的第三天!今天,我們將探索運算子和表達式——在程式中執行計算、制定決策和編寫有意義的邏輯的基本工具。
運算子是對值或變數執行運算的特殊符號或關鍵字。這些操作的範圍可以從算術計算到邏輯決策。
用於數學運算,如加法、減法、乘法等
Operator | Description | Example | Output |
---|---|---|---|
Addition | 5 3 | 8 | |
- | Subtraction | 10 - 6 | 4 |
* | Multiplication | 4 * 2 | 8 |
/ | Division | 12 / 4 | 3 |
% | Modulus (Remainder) | 10 % 3 | 1 |
** | Exponentiation | 2 ** 3 | 8 |
let num1 = 10; let num2 = 3; console.log(num1 + num2); // 13 console.log(num1 % num2); // 1
Operator | Description | Example | Output |
---|---|---|---|
== | Equal to | 5 == "5" | true |
=== | Strict equal to | 5 === "5" | false |
!= | Not equal to | 5 != "5" | false |
!== | Strict not equal | 5 !== "5" | true |
< | Less than | 5 < 10 | true |
> | Greater than | 10 > 5 | true |
<= | Less than or equal | 5 <= 5 | true |
>= | Greater than or equal | 10 >= 5 | true |
let num1 = 10; let num2 = 3; console.log(num1 + num2); // 13 console.log(num1 % num2); // 1
組合多個條件或反轉邏輯。
Operator | Description | Example | Output |
---|---|---|---|
&& | Logical AND | true && false | false |
` | ` | Logical OR | |
! | Logical NOT | !true | false |
let age = 20; console.log(age >= 18); // true console.log(age === "20"); // false
Operator | Description | Example | Output |
---|---|---|---|
= | Assign | x = 10 | 10 |
= | Add and assign | x = 5 | x = x 5 |
-= | Subtract and assign | x -= 3 | x = x - 3 |
*= | Multiply and assign | x *= 2 | x = x * 2 |
/= | Divide and assign | x /= 2 | x = x / 2 |
%= | Modulus and assign | x %= 3 | x = x % 3 |
let isAdult = true; let hasID = false; console.log(isAdult && hasID); // false console.log(isAdult || hasID); // true
Operator | Description | Precedence |
---|---|---|
** | Exponentiation | 1 |
*, /, % | Multiplication, Division, Modulus | 2 |
, - | Addition, Subtraction | 3 |
<, >, ==, != | Comparison | 4 |
&& | Logical AND | 5 |
` | ` |
let num1 = 10; let num2 = 3; console.log(num1 + num2); // 13 console.log(num1 % num2); // 1
使用括號 () 控制優先權。
let age = 20; console.log(age >= 18); // true console.log(age === "20"); // false
今天,我們介紹了:
在第 4 天,我們將學習 JavaScript 中的控制流,重點關注條件語句和循環。敬請期待 2024 年 12 月 11 日!
以上是JavaScript 中的運算子和表達式的詳細內容。更多資訊請關注PHP中文網其他相關文章!