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 |
最佳实践建议:
使用对象组织相关数据和功能
优先使用点表示法访问属性,特殊属性名使用方括号
使用
Math.floor(Math.random() * range)
生成随机整数需要精确小数计算时考虑使用
.toFixed()
利用解构语法简化对象操作:
const {name, age} = person;
使用
Math
对象进行数学运算而非自行实现