当前位置: 首页 > news >正文

JavaScript学习教程,从入门到精通,JavaScript 运算符及语法知识点详解(8)

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)

代码说明:

  1. 函数定义:使用function关键字定义计算立方体体积的函数
  2. 算术运算符:使用*计算三个维度的乘积
  3. 赋值运算符:使用=为变量赋值
  4. 比较运算符:使用>检查输入是否有效
  5. 逻辑运算符:使用&&确保所有尺寸都大于0
  6. 条件运算符:使用?:根据体积大小分类
  7. 位运算符:使用&~进行位运算示例
  8. 运算符优先级:演示了复杂表达式中的运算顺序

三、案例代码

下面我将提供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运算符在实际开发中的多种应用场景,包括:

  1. 电商计算(算术、比较、条件运算符)
  2. 游戏开发(位、逻辑、赋值运算符)
  3. 表单验证(比较、逻辑运算符)
  4. 工具类开发(算术、比较、条件运算符)
  5. DOM操作和动画(赋值、算术、位运算符)
http://www.dtcms.com/a/122032.html

相关文章:

  • 2025年Java无服务器架构实战:AWS Lambda与Spring Cloud Function深度整合
  • uniapp 打包 H5 向 打包的APP 使用 @dcloudio/uni-webview-js 传值
  • 数据结构实验4.3:利用队列实现杨辉三角的输出
  • BOTA六维力矩传感器在三层AI架构中的集成实践:从数据采集到力控闭环
  • 绿算技术团队受邀出席英伟达GTC2025大会丨重塑AI存储新范式
  • 【android bluetooth 框架分析 01】【关键线程 3】【bt_jni_thread 线程介绍】
  • MySQL多表查询实战指南:从SQL到XML映射的完整实现(2W+字深度解析)
  • [Windows] Gopeed-v1.7.0
  • HashMap、LinkedHashMap与TreeMap的核心特性与使用场景总结
  • Navicat 17 for Mac 数据库管理
  • C语言资源自动释放实现详解:基于GCC cleanup属性
  • Socket通信保护概论,Android系列
  • SAP-ABAP:SAP PO接口中System Landscape(SL Landscape Directory,SLD)作用详解
  • windows11下pytorch(cpu)安装
  • 记录一次SSH和SFTP服务分离后文件上传权限问题
  • AI比人脑更强,因为被植入思维模型【52】福格行为模型
  • 0303hooks-react-仿低代码平台项目
  • OSPF的数据报文格式【复习篇】
  • 算法基础—二分算法
  • STM32 vs ESP32:如何选择最适合你的单片机?
  • 网络协议学习
  • PDFtk
  • 2025年3月全国青少年软件编程等级考试(Python六级)试卷及答案
  • 带无源位置反馈气动V型调节开关球阀的特点解析-耀圣
  • find指令中使用正则表达式
  • C++中STL学习(一)——向量、栈、堆、集合
  • PyQt6实例_A股财报数据维护工具_解说并数据与完整代码分享
  • ISP的过程
  • 用户注册(阿里云手机验证码)
  • CNN(卷积神经网络)