JavaScript 運算符及語法知識點詳解
一、JavaScript 運算符
1. 算術運算符
用于執行數學運算:
+
加法-
減法*
乘法/
除法%
取模(余數)++
遞增--
遞減**
冪運算(ES6)
let a = 10, b = 3;
console.log(a + b); // 13
console.log(a - b); // 7
console.log(a * b); // 30
console.log(a / b); // 3.333...
console.log(a % b); // 1
console.log(a++); // 10 (先返回后加)
console.log(++a); // 12 (先加后返回)
console.log(a ** b); // 1728 (12的3次方)
2. 賦值運算符
用于給變量賦值:
=
簡單賦值+=
加后賦值-=
減后賦值*=
乘后賦值/=
除后賦值%=
取模后賦值**=
冪運算后賦值
let x = 5;
x += 3; // 等同于 x = x + 3 → 8
x -= 2; // 等同于 x = x - 2 → 6
x *= 4; // 等同于 x = x * 4 → 24
x /= 3; // 等同于 x = x / 3 → 8
x %= 5; // 等同于 x = x % 5 → 3
x **= 2; // 等同于 x = x ** 2 → 9
3. 比較運算符
用于比較值:
==
等于(值相等)===
嚴格等于(值和類型都相等)!=
不等于!==
嚴格不等于>
大于<
小于>=
大于等于<=
小于等于
console.log(5 == '5'); // true (類型轉換)
console.log(5 === '5'); // false
console.log(5 != '5'); // false
console.log(5 !== '5'); // true
console.log(5 > 3); // true
console.log(5 < 3); // false
4. 條件(三元)運算符
condition ? expr1 : expr2
- 如果條件為真則執行expr1,否則執行expr2
let age = 20;
let status = (age >= 18) ? '成人' : '未成年';
console.log(status); // 成人
5. 布爾(邏輯)運算符
&&
邏輯與||
邏輯或!
邏輯非
let hasLicense = true, hasCar = false;
console.log(hasLicense && hasCar); // false
console.log(hasLicense || hasCar); // true
console.log(!hasLicense); // false
6. 位運算符
對二進制位進行操作:
&
與|
或~
非^
異或<<
左移>>
右移>>>
無符號右移
let num1 = 5; // 0101
let num2 = 3; // 0011
console.log(num1 & num2); // 0001 → 1
console.log(num1 | num2); // 0111 → 7
console.log(~num1); // 1010 → -6
console.log(num1 ^ num2); // 0110 → 6
console.log(num1 << 1); // 1010 → 10
console.log(num1 >> 1); // 0010 → 2
7. 運算符優先級
運算符按優先級從高到低執行,同級別從左到右:
優先級 | 運算符 |
---|---|
高 | () 括號 |
++ -- 后置遞增/減 | |
! ~ 邏輯非/位非 | |
+ - 一元加減 | |
++ -- 前置遞增/減 | |
** 冪運算 | |
* / % 乘除模 | |
+ - 加減 | |
<< >> >>> 位移 | |
< <= > >= 比較 | |
== != === !== 等值 | |
& 位與 | |
^ 位異或 | |
` | |
&& 邏輯與 | |
` | |
低 | ?: 條件運算符 |
= 賦值 |
let result = 5 + 3 * 2 ** 2; // 3*4=12 → 5+12=17
console.log(result); // 17
二、案例代碼:計算立方體的體積
/*** 計算立方體體積的函數* @param {number} length - 立方體的長度* @param {number} width - 立方體的寬度* @param {number} height - 立方體的高度* @returns {number} 立方體的體積*/
function calculateCubeVolume(length, width, height) {// 使用算術運算符*計算體積let volume = length * width * height;// 返回計算結果return volume;
}// 使用賦值運算符定義立方體尺寸
let cubeLength = 5;
let cubeWidth = 4;
let cubeHeight = 3;// 調用函數計算體積
let cubeVolume = calculateCubeVolume(cubeLength, cubeWidth, cubeHeight);// 使用比較運算符驗證輸入是否有效
if (cubeLength > 0 && cubeWidth > 0 && cubeHeight > 0) {// 使用字符串連接運算符+輸出結果console.log("立方體的尺寸: 長" + cubeLength + ", 寬" + cubeWidth + ", 高" + cubeHeight);console.log("立方體的體積是: " + cubeVolume);// 使用條件運算符判斷立方體大小let sizeCategory = cubeVolume > 50 ? "大" : "小";console.log("這是一個" + sizeCategory + "型立方體");// 使用位運算符示例(雖然不太適用于此場景)let roundedVolume = cubeVolume & ~1; // 向下舍入到最近的偶數console.log("向下舍入到最近的偶數: " + roundedVolume);
} else {console.log("錯誤: 所有尺寸必須大于0");
}// 運算符優先級示例
let complexCalculation = (cubeLength + cubeWidth) * cubeHeight ** 2 / 4;
console.log("復雜計算結果: " + complexCalculation);
// 解釋: 先計算指數(cubeHeight ** 2 = 9), 然后加法(5+4=9),
// 然后乘法(9*9=81), 最后除法(81/4=20.25)
代碼說明:
- 函數定義:使用
function
關鍵字定義計算立方體體積的函數 - 算術運算符:使用
*
計算三個維度的乘積 - 賦值運算符:使用
=
為變量賦值 - 比較運算符:使用
>
檢查輸入是否有效 - 邏輯運算符:使用
&&
確保所有尺寸都大于0 - 條件運算符:使用
?:
根據體積大小分類 - 位運算符:使用
&
和~
進行位運算示例 - 運算符優先級:演示了復雜表達式中的運算順序
三、案例代碼
下面我將提供5個實際開發中常見的案例,每個案例都會充分利用不同的JavaScript運算符。
案例1:電商網站購物車計算
/*** 計算購物車總價和折扣* @param {Array} cartItems - 購物車商品數組* @param {string} promoCode - 優惠碼* @returns {Object} 包含總價、折扣和應付金額的對象*/
function calculateCartTotal(cartItems, promoCode) {// 使用算術運算符計算商品小計let subtotal = cartItems.reduce((sum, item) => sum + (item.price * item.quantity), 0);// 使用比較運算符驗證優惠碼let discount = 0;if (promoCode === 'SAVE20' && subtotal >= 100) {// 使用賦值運算符應用折扣discount = subtotal * 0.2;} else if (promoCode === 'SAVE10') {discount = subtotal * 0.1;}// 使用條件運算符確定是否免運費const shippingFee = subtotal > 50 ? 0 : 5.99;// 計算總價(使用算術運算符)const total = subtotal - discount + shippingFee;return {subtotal: +subtotal.toFixed(2), // 使用一元+運算符轉換為數字discount: +discount.toFixed(2),shippingFee,total: +total.toFixed(2)};
}// 測試數據
const cart = [{ name: '無線耳機', price: 99.99, quantity: 1 },{ name: '手機殼', price: 15.50, quantity: 2 },{ name: '充電器', price: 29.99, quantity: 1 }
];// 計算不同優惠碼情況
console.log('使用SAVE20優惠碼:', calculateCartTotal(cart, 'SAVE20'));
console.log('使用SAVE10優惠碼:', calculateCartTotal(cart, 'SAVE10'));
console.log('無優惠碼:', calculateCartTotal(cart, ''));
案例2:游戲角色狀態管理
class GameCharacter {constructor(name, health, strength, agility) {this.name = name;this.maxHealth = health;this.health = health; // 當前生命值this.strength = strength;this.agility = agility;this.isAlive = true;this.skills = [];}// 使用算術運算符計算傷害attack(target) {if (!this.isAlive || !target.isAlive) return false;// 使用位運算符生成隨機因子const critChance = this.agility & 0xF; // 取低4位作為暴擊率const isCritical = Math.random() * 100 < critChance;// 使用條件運算符確定傷害值let damage = this.strength + (isCritical ? this.strength >> 1 : 0);// 使用比較運算符驗證目標是否存活target.takeDamage(damage);return { damage, isCritical };}// 使用賦值運算符減少生命值takeDamage(amount) {this.health -= amount;// 使用邏輯運算符檢查角色狀態this.isAlive = this.health > 0;if (!this.isAlive) {console.log(`${this.name}已被擊敗!`);}}// 使用算術運算符恢復生命值heal(amount) {// 使用比較運算符確保不超過最大生命值this.health = Math.min(this.health + amount, this.maxHealth);console.log(`${this.name}恢復了${amount}點生命值`);}// 使用條件運算符添加技能learnSkill(skill) {this.skills.includes(skill) ? console.log(`${this.name}已經學會了${skill}`): (this.skills.push(skill), console.log(`${this.name}學會了新技能: ${skill}`));}
}// 創建角色
const hero = new GameCharacter('英雄', 100, 15, 12);
const monster = new GameCharacter('怪物', 80, 12, 8);// 戰斗模擬
while (hero.isAlive && monster.isAlive) {const attackResult = hero.attack(monster);if (attackResult) {console.log(`${hero.name}對${monster.name}造成了${attackResult.damage}點傷害${attackResult.isCritical ? '(暴擊!)' : ''}`);}if (monster.isAlive) {monster.attack(hero);}
}
案例3:表單驗證工具
/*** 表單驗證工具類*/
class FormValidator {constructor(formId) {this.form = document.getElementById(formId);this.errors = [];}// 使用比較運算符驗證必填字段validateRequired(fieldName, message) {const field = this.form[fieldName];if (!field || !field.value.trim()) {this.errors.push(message || `${fieldName}是必填字段`);return false;}return true;}// 使用算術運算符驗證數字范圍validateNumberRange(fieldName, min, max, message) {const field = this.form[fieldName];if (!field) return false;const value = +field.value; // 使用一元+運算符轉換為數字if (isNaN(value) || value < min || value > max) {this.errors.push(message || `${fieldName}必須在${min}到${max}之間`);return false;}return true;}// 使用比較運算符驗證郵箱格式validateEmail(fieldName, message) {const field = this.form[fieldName];if (!field) return false;const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;if (!emailRegex.test(field.value)) {this.errors.push(message || '請輸入有效的郵箱地址');return false;}return true;}// 使用比較運算符驗證密碼匹配validatePasswordMatch(passwordField, confirmField, message) {const password = this.form[passwordField];const confirm = this.form[confirmField];if (!password || !confirm || password.value !== confirm.value) {this.errors.push(message || '兩次輸入的密碼不匹配');return false;}return true;}// 使用邏輯運算符組合驗證結果validate() {this.errors = [];// 驗證用戶名this.validateRequired('username', '請輸入用戶名');// 驗證郵箱this.validateRequired('email');this.validateEmail('email');// 驗證年齡this.validateRequired('age');this.validateNumberRange('age', 18, 100, '年齡必須在18到100歲之間');// 驗證密碼this.validateRequired('password', '請輸入密碼');this.validateRequired('confirmPassword', '請確認密碼');this.validatePasswordMatch('password', 'confirmPassword');// 使用位運算符檢查錯誤數量return this.errors.length === 0;}getErrors() {return this.errors;}
}// 使用示例
document.getElementById('myForm').addEventListener('submit', function(e) {e.preventDefault();const validator = new FormValidator('myForm');if (validator.validate()) {alert('表單驗證通過,即將提交!');// 提交表單...} else {alert('請修正以下錯誤:\n' + validator.getErrors().join('\n'));}
});
案例4:溫度轉換工具
/*** 溫度轉換工具*/
class TemperatureConverter {// 使用算術運算符進行溫度轉換static celsiusToFahrenheit(celsius) {return (celsius * 9/5) + 32;}static fahrenheitToCelsius(fahrenheit) {return (fahrenheit - 32) * 5/9;}// 使用比較運算符驗證輸入static isValidTemperature(temp, scale) {switch(scale.toUpperCase()) {case 'C':return temp >= -273.15; // 絕對零度case 'F':return temp >= -459.67; // 絕對零度(華氏)default:return false;}}// 使用條件運算符選擇轉換方法static convert(temp, fromScale, toScale) {if (!this.isValidTemperature(temp, fromScale)) {throw new Error('無效的溫度值');}fromScale = fromScale.toUpperCase();toScale = toScale.toUpperCase();if (fromScale === toScale) {return temp;}return fromScale === 'C' ? this.celsiusToFahrenheit(temp): this.fahrenheitToCelsius(temp);}// 使用位運算符生成隨機溫度(演示用途)static getRandomTemp(scale) {const random = Math.random() * 100 | 0; // 使用位或取整return scale.toUpperCase() === 'C' ? random : this.celsiusToFahrenheit(random);}
}// 使用示例
const currentTempC = 25;
const currentTempF = TemperatureConverter.celsiusToFahrenheit(currentTempC);
console.log(`${currentTempC}°C = ${currentTempF.toFixed(1)}°F`);const testTemp = 98.6;
console.log(`${testTemp}°F = ${TemperatureConverter.fahrenheitToCelsius(testTemp).toFixed(1)}°C`);// 隨機溫度生成
const randomCTemp = TemperatureConverter.getRandomTemp('C');
const randomFTemp = TemperatureConverter.getRandomTemp('F');
console.log(`隨機溫度: ${randomCTemp}°C / ${randomFTemp}°F`);// 邊界測試
try {console.log(TemperatureConverter.convert(-300, 'C', 'F'));
} catch (e) {console.error(e.message); // 無效的溫度值
}
案例5:DOM元素動畫控制器
class ElementAnimator {constructor(elementId) {this.element = document.getElementById(elementId);this.animationId = null;this.isAnimating = false;this.position = 0;this.speed = 5;this.direction = 1; // 1 for right, -1 for left}// 使用算術運算符更新位置updatePosition() {// 使用賦值運算符更新位置this.position += this.speed * this.direction;// 使用比較運算符檢查邊界const maxPosition = window.innerWidth - this.element.offsetWidth;if (this.position >= maxPosition || this.position <= 0) {// 使用位運算符取反方向(演示用途)this.direction = ~this.direction + 1; // 等同于 this.direction *= -1}// 使用條件運算符設置樣式this.element.style.transform = `translateX(${this.position}px)`;}// 使用邏輯運算符控制動畫狀態start() {if (this.isAnimating) return;this.isAnimating = true;const animate = () => {this.updatePosition();this.animationId = requestAnimationFrame(animate);};animate();}stop() {if (!this.isAnimating) return;cancelAnimationFrame(this.animationId);this.isAnimating = false;}// 使用算術運算符調整速度increaseSpeed() {this.speed = Math.min(this.speed + 1, 20); // 最大速度20}decreaseSpeed() {this.speed = Math.max(this.speed - 1, 1); // 最小速度1}// 使用條件運算符切換方向toggleDirection() {this.direction *= -1;}
}// 使用示例
const animator = new ElementAnimator('animatedElement');document.getElementById('startBtn').addEventListener('click', () => {animator.start();
});document.getElementById('stopBtn').addEventListener('click', () => {animator.stop();
});document.getElementById('speedUpBtn').addEventListener('click', () => {animator.increaseSpeed();
});document.getElementById('slowDownBtn').addEventListener('click', () => {animator.decreaseSpeed();
});document.getElementById('toggleDirBtn').addEventListener('click', () => {animator.toggleDirection();
});// 鍵盤控制(使用位運算符檢測按鍵組合)
document.addEventListener('keydown', (e) => {// 使用位掩碼檢查Ctrl鍵(演示用途)const ctrlPressed = e.ctrlKey;switch(e.key) {case 'ArrowRight':if (ctrlPressed) animator.increaseSpeed();else if (animator.direction !== 1) animator.toggleDirection();break;case 'ArrowLeft':if (ctrlPressed) animator.decreaseSpeed();else if (animator.direction !== -1) animator.toggleDirection();break;case ' ':animator.isAnimating ? animator.stop() : animator.start();break;}
});
這些案例涵蓋了JavaScript運算符在實際開發中的多種應用場景,包括:
- 電商計算(算術、比較、條件運算符)
- 游戲開發(位、邏輯、賦值運算符)
- 表單驗證(比較、邏輯運算符)
- 工具類開發(算術、比較、條件運算符)
- DOM操作和動畫(賦值、算術、位運算符)