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

JavaScript对象与Math对象完全指南

JavaScript 对象与Math对象完全指南

对象基础概念与操作

对象是什么?

  • 数据集合:包含相关数据和功能的容器

  • 结构组成

    • 属性:描述对象特征的变量(名词性)

    • 方法:对象可执行的操作(动词性,本质是函数)

对象创建与访问

// 创建对象
let person = {// 属性name: "张三",age: 28,profession: "软件工程师",// 方法introduce() {return `大家好,我是${this.name},今年${this.age}岁`;},work() {return `${this.name}正在编写代码...`;}
};
​
// 访问属性
console.log(person.name); // "张三"
console.log(person["profession"]); // "软件工程师"
​
// 调用方法
console.log(person.introduce()); // "大家好,我是张三,今年28岁"
console.log(person.work()); // "张三正在编写代码..."

对象动态操作

// 创建空对象
let car = {};
​
// 动态添加属性
car.brand = "Tesla";
car.model = "Model 3";
car.year = 2023;
​
// 动态添加方法
car.start = function() {return `${this.brand} ${this.model} 已启动!`;
};
​
console.log(car.start()); // "Tesla Model 3 已启动!"

遍历对象

// for...in 循环遍历
for (let key in car) {console.log(`${key}: ${car[key]}`);
}

对象数组操作

const products = [{ id: 1, name: "无线耳机", price: 199, stock: 50 },{ id: 2, name: "智能手表", price: 899, stock: 25 },{ id: 3, name: "平板电脑", price: 2399, stock: 10 }
];
​
// 渲染产品列表
function renderProducts() {let output = "<h2>产品列表</h2><ul>";products.forEach(product => {output += `<li><strong>${product.name}</strong><br>价格: ¥${product.price.toFixed(2)} | 库存: ${product.stock}件</li>`;});output += "</ul>";document.body.innerHTML = output;
}
​
renderProducts();

数学计算利器:Math对象

常用属性

console.log("圆周率:", Math.PI); // 3.141592653589793
console.log("自然常数:", Math.E); // 2.718281828459045
console.log("2的自然对数:", Math.LN2); // 0.6931471805599453

核心方法详解

1. 随机数生成
// 生成0-1之间的随机数
const random = Math.random();
console.log("基础随机数:", random);
​
// 生成1-100的随机整数
const randomInt = Math.floor(Math.random() * 100) + 1;
console.log("1-100随机整数:", randomInt);
​
// 生成指定范围的随机数函数
function randomRange(min, max) {return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log("50-100随机数:", randomRange(50, 100));
2. 取整方法对比
// 向上取整
console.log("Math.ceil(4.2):", Math.ceil(4.2)); // 5
console.log("Math.ceil(-3.7):", Math.ceil(-3.7)); // -3
​
// 向下取整
console.log("Math.floor(4.9):", Math.floor(4.9)); // 4
console.log("Math.floor(-3.7):", Math.floor(-3.7)); // -4
​
// 四舍五入
console.log("Math.round(4.4):", Math.round(4.4)); // 4
console.log("Math.round(4.5):", Math.round(4.5)); // 5
console.log("Math.round(-3.7):", Math.round(-3.7)); // -4
3. 极值计算
const temperatures = [22, 19, 25, 18, 27, 21];
​
console.log("最高温度:", Math.max(...temperatures)); // 27
console.log("最低温度:", Math.min(...temperatures)); // 18
console.log("最大值:", Math.max(10, 25, 37, 42, 15)); // 42
4. 幂运算与开方
// 幂运算
console.log("2的10次方:", Math.pow(2, 10)); // 1024
console.log("立方运算:", Math.pow(5, 3)); // 125
​
// 开方运算
console.log("16的平方根:", Math.sqrt(16)); // 4
console.log("64的立方根:", Math.cbrt(64)); // 4
​
// 勾股定理应用
function hypotenuse(a, b) {return Math.sqrt(a * a + b * b);
}
console.log("直角边3和4的斜边:", hypotenuse(3, 4)); // 5

三角函数方法

// 角度转弧度
const degrees = 45;
const radians = degrees * (Math.PI / 180);
​
console.log("45度的正弦值:", Math.sin(radians)); // ≈0.707
console.log("45度的余弦值:", Math.cos(radians)); // ≈0.707
console.log("45度的正切值:", Math.tan(radians)); // ≈1

实际应用场景

1. 生成验证码

function generateCaptcha(length = 6) {const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';let captcha = '';for (let i = 0; i < length; i++) {const randomIndex = Math.floor(Math.random() * chars.length);captcha += chars[randomIndex];}return captcha;
}
​
console.log("验证码:", generateCaptcha());

2. 价格格式化

const products = [{ name: "笔记本电脑", price: 6580.5 },{ name: "智能手机", price: 3999 },{ name: "耳机", price: 899.99 }
];
​
// 价格格式化函数
function formatPrice(price) {return "¥" + Math.round(price).toLocaleString();
}
​
// 显示格式化后的价格
products.forEach(product => {console.log(`${product.name}: ${formatPrice(product.price)}`);
});

3. 游戏开发应用

class Player {constructor(name) {this.name = name;this.health = 100;this.attackPower = Math.floor(Math.random() * 10) + 5;}attack(target) {const damage = Math.floor(Math.random() * this.attackPower) + 1;target.health = Math.max(0, target.health - damage);return damage;}
}
​
// 创建玩家
const player1 = new Player("勇士");
const player2 = new Player("恶龙");
​
// 模拟战斗
console.log(`${player1.name} 攻击 ${player2.name}`);
const damage = player1.attack(player2);
console.log(`造成 ${damage} 点伤害,${player2.name} 生命值: ${player2.health}`);

关键知识点总结

概念描述示例
对象属性描述对象特征的数据person.name
对象方法对象可执行的操作person.introduce()
动态成员运行时添加的属性/方法car.color = 'red'
Math.PI圆周率常数Math.PI ≈ 3.14
Math.random()生成[0,1)随机数随机数生成基础
Math.floor()向下取整Math.floor(4.9)→4
Math.ceil()向上取整Math.ceil(4.1)→5
Math.round()四舍五入Math.round(4.5)→5
Math.max()最大值计算Math.max(1,5,3)→5
Math.min()最小值计算Math.min(1,5,3)→1
Math.pow()幂运算Math.pow(2,3)→8
Math.sqrt()平方根计算Math.sqrt(16)→4

最佳实践建议

  1. 使用对象组织相关数据和功能

  2. 优先使用点表示法访问属性,特殊属性名使用方括号

  3. 使用Math.floor(Math.random() * range)生成随机整数

  4. 需要精确小数计算时考虑使用.toFixed()

  5. 利用解构语法简化对象操作:const {name, age} = person;

  6. 使用Math对象进行数学运算而非自行实现

http://www.dtcms.com/a/303046.html

相关文章:

  • 力扣7:整数反转
  • 利用DataStream和TrafficPeak实现大数据可观察性
  • jQuery 最新语法大全详解(2025版)
  • 下载k8s官方组件chart和容器镜像
  • JavaScript中的Promise.all方法详解
  • 坚鹏:AI智能体培训是知行学成为AI智能体创新应用引领者的基础
  • 【归并排序】排序数组(medium)
  • 阿里云【免费试用】Elasticsearch 智能运维 AI 助手
  • 应用信息更新至1.18.0
  • 加法器 以及ALU(逻辑算术单元)
  • 深入解析 Spring 获取 XML 验证模式的过程
  • redis数据库的四种取得 shell方法
  • C++模板进阶:从基础到实战的深度探索
  • python生成 requirement.txt 文件
  • 一个高效的阿里云漏洞库爬虫工具,用于自动化爬取和处理CVE数据
  • ROS2入门之开发环境搭建
  • AI-调查研究-40-多模态大模型量化 格局重塑:五大开源模型横评与技术对比
  • Navicat 17 教程:Windows 和 Mac 系统适用
  • 【运维】Smartctl安装及使用指南
  • Python爬虫实战:快速采集教育政策数据(附官网工具库API)
  • 设计模式实战:自定义SpringIOC(亲手实践)
  • 常见依赖于TCP/IP的应用层协议
  • Taro 网络请求相关 API 全面解析
  • 初识opencv05——图像预处理4
  • 【Linux系统】Ext2文件系统 | 软硬链接
  • 接口测试核心概念与实践指南
  • 分享一个脚本,从mysql导出数据csv到hdfs临时目录
  • Vue中Computed与Watch的深度解析:缓存机制与适用场景
  • LeetCode 214:最短回文串
  • Leetcode148. 排序链表 中遇到的错误