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操作和动画(赋值、算术、位运算符)