理解 JavaScript 运算符
在 JavaScript 中,运算符是用于对值和变量执行运算的特殊符号或关键字。它们允许我们操纵数据并控制代码流。让我们分解一下最常用的运算符类型及其用途:
1️⃣赋值运算符(=)
赋值运算符用于给变量赋值。
📌示例:
let x = 10 // Assigns the value 10 to variable x let y = 5 // Assigns the value 5 to variable y
2️⃣ 算术运算符
算术运算符对数字执行基本的数学运算。
📌示例:
console.log("x + y = " + (x + y)) // Output: x + y = 15 console.log("x - y = " + (x - y)) // Output: x - y = 5 console.log("x / y = " + (x / y)) // Output: x / y = 2 console.log("x * y = " + (x * y)) // Output: x * y = 50 console.log("x % y = " + (x % y)) // Output: x % y = 0 console.log("(x**y) = " + (x**y)) // Output: (x**y) = 100000 console.log("(++x) = " + (++x)) // Output: (++x) = 11 console.log("(x++) = " + (x++)) // Output: (x++) = 11 console.log("(--y) = " + (--y)) // Output: (--y) = 4 console.log("(y--) = " + (y--)) // Output: (y--) = 4
3️⃣ 比较运算符
比较运算符比较两个值并返回布尔值(“true”或“false”)。这些通常用于循环和分支语句中。
📌示例:
console.log("(x == y) = " + (x == y)) // Output: (x == y) = false console.log("(x != y) = " + (x != y)) // Output: (x != y) = true // Compares datatypes also console.log("(x === y) = " + (x === y)) // Output: (x === y) = false // Compares datatypes also console.log("(x !== y) = " + (x !== y)) // Output: (x !== y) = true console.log("(x > y) = " + (x > y)) // Output: (x > y) = true console.log("(x >= y) = " + (x >= y)) // Output: (x >= y) = true console.log("(y < x) = " + (y < x)) // Output: (y < x) = true console.log("(y <= x) = " + (y <= x)) // Output: (y <= x) = true
4️⃣ 逻辑运算符
逻辑运算符用于执行逻辑运算并返回布尔值(“true”或“false”)。
📌示例:
let isValidNumber = (x > 8 && 8 > y) // If both condition are correct returns true otherwise false console.log("(x > 8 && 8 > y) = " + isValidNumber) // Output: (x > 8 && 8 > y) = true let isValidCheck = (x > 20 || 8 > y) // If one of condition is correct returns true otherwise false console.log("(x > 20 || 8 > y) = " + isValidCheck) // Output: (x > 20 || 8 > y) = true let isValid = false console.log("(!isValid) = " + !isValid) // Output: (!isValid) = true
5️⃣字符串运算符
+ 运算符用途广泛,可以与字符串一起使用以进行连接(连接两个字符串)。与数字一起使用时,它会执行加法。
📌示例:
// Concatenation console.log("Richa " + "webDev") // Output: Richa webDev // Addition console.log(10 + 5) // Output: 15
6️⃣三元运算符(?:)
三元运算符是执行条件检查的简洁方法。如果条件为真,则返回一个值;如果条件为假,则返回另一个值。
🟤 语法:
condition ? valueIfTrue : valueIfFalse;
📌示例:
const isEven = 10 % 2 === 0 ? "Number is even" : "Number is old" console.log("isEven = " + isEven) // Output: isEven = Number is even
💡 脑筋急转弯
解释为什么涉及 `num++`、`--num` 和 `num--` 操作的代码片段的输出结果为 21。请在下方评论。
let num = 20 console.log("num = " + num) // Output: (++num) = 21 console.log("(++num) = " + (++num)) // Output: (++num) = 21 console.log("(num++) = " + (num++)) // Output: (num++) = 21 console.log("(--num) = " + (--num)) // Output: (--num) = 21 console.log("(num--) = " + (num--)) // Output: (num--) = 21
输出:
num = 20 (++num) = 21 (num++) = 21 (--num) = 21 (num--) = 21
结论
JavaScript 运算符是帮助您编写有效且高效的代码的基本构建块。通过掌握它们,您可以执行各种操作,从简单的赋值到复杂的逻辑检查。尝试使用这些运算符以更好地了解它们的行为!
祝你编码愉快✨