JavaScript 核心对象深度解析:Math、Date 与 String
JavaScript 作为 Web 开发的核心语言,提供了丰富的内置对象来简化编程工作。本文将深入探讨三个重要的内置对象:Math、Date 和 String,通过详细的代码示例和综合案例帮助你全面掌握它们的用法。
一、Math 对象
Math 对象提供了一系列静态属性和方法,用于执行各种数学运算,无需实例化即可使用。
常用属性:
console.log(Math.PI); // 圆周率: 3.141592653589793
console.log(Math.E); // 自然常数: 2.718281828459045
console.log(Math.SQRT2); // 根号2: 1.4142135623730951
常用方法:
// 1. 取整方法
console.log(Math.floor(3.9)); // 向下取整: 3
console.log(Math.ceil(3.1)); // 向上取整: 4
console.log(Math.round(3.5)); // 四舍五入: 4// 2. 最值与绝对值
console.log(Math.max(10, 5, 20)); // 最大值: 20
console.log(Math.min(10, 5, 20)); // 最小值: 5
console.log(Math.abs(-10)); // 绝对值: 10// 3. 幂运算与平方根
console.log(Math.pow(2, 3)); // 2的3次方: 8
console.log(Math.sqrt(16)); // 平方根: 4// 4. 随机数生成
console.log(Math.random()); // 生成0-1之间的随机小数
// 生成1-10之间的随机整数
console.log(Math.floor(Math.random() * 10) + 1);
综合案例1:随机验证码生成器
function generateCode(length) {const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';let code = '';for (let i = 0; i < length; i++) {const randomIndex = Math.floor(Math.random() * chars.length);code += chars.charAt(randomIndex);}return code;
}console.log(generateCode(6)); // 输出类似 "A3B7E9" 的随机验证码
综合案例2:定义一个随机数生成函数
function getRandomNumber(min, max) {return Math.floor(Math.random() * (max - min + 1)) + min;
}
二、Date 对象
Date 对象用于处理日期和时间,提供了创建、操作和格式化日期的方法。
创建 Date 对象:
// 当前时间
const now = new Date();
console.log(now); // 输出当前日期时间,如: 2023-10-15T08:30:00.000Z// 指定日期时间 (年, 月[0-11], 日, 时, 分, 秒, 毫秒)
const specificDate = new Date(2023, 9, 15, 8, 30, 0, 0);
console.log(specificDate); // 2023-10-15T00:30:00.000Z (注意月份是从0开始的)// 从时间戳创建
const timestamp = 1634286600000; // 某个时间点的毫秒数
const dateFromTimestamp = new Date(timestamp);
console.log(dateFromTimestamp);
获取日期信息:
const date = new Date();
console.log(date.getFullYear()); // 年份: 2023
console.log(date.getMonth() + 1); // 月份: 1-12 (注意要+1)
console.log(date.getDate()); // 日: 1-31
console.log(date.getDay()); // 星期: 0-6 (0是星期日)
console.log(date.getHours()); // 小时: 0-23
console.log(date.getMinutes()); // 分钟: 0-59
console.log(date.getSeconds()); // 秒: 0-59
console.log(date.getMilliseconds());// 毫秒: 0-999
console.log(date.getTime()); // 时间戳: 1970年1月1日至今的毫秒数
设置日期信息:
const date = new Date();
date.setFullYear(2024); // 设置年份
date.setMonth(11); // 设置月份 (11代表12月)
date.setDate(25); // 设置日
date.setHours(14); // 设置小时
date.setMinutes(30); // 设置分钟
date.setSeconds(0); // 设置秒
console.log(date); // 输出: 2024-12-25T06:30:00.000Z
日期计算与比较:
// 计算未来7天的日期
const today = new Date();
const nextWeek = new Date(today);
nextWeek.setDate(today.getDate() + 7);
console.log(nextWeek);// 比较两个日期
const date1 = new Date(2023, 0, 1);
const date2 = new Date(2023, 11, 31);
console.log(date1 < date2); // true
console.log(date1.getTime() - date2.getTime()); // 相差的毫秒数
日期格式化:
const date = new Date();// 自定义格式化
function formatDate(date) {const year = date.getFullYear();const month = String(date.getMonth() + 1).padStart(2, '0');const day = String(date.getDate()).padStart(2, '0');return `${year}-${month}-${day}`;
}
console.log(formatDate(date)); // 输出: 2023-10-15// 使用内置方法格式化
console.log(date.toLocaleDateString()); // 根据本地语言环境格式化日期
console.log(date.toISOString()); // 国际标准格式: 2023-10-15T08:30:00.000Z
综合案例:倒计时功能
function countdown(targetDate) {const now = new Date();const diff = targetDate.getTime() - now.getTime();// 计算剩余天数、小时、分钟和秒const days = Math.floor(diff / (1000 * 60 * 60 * 24));const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));const seconds = Math.floor((diff % (1000 * 60)) / 1000);return `${days}天 ${hours}小时 ${minutes}分 ${seconds}秒`;
}// 计算距离2024年新年的倒计时
const newYear = new Date(2024, 0, 1);
console.log(countdown(newYear)); // 输出: "XX天 XX小时 XX分 XX秒"
三、String 对象:文本处理的全能工具
String 对象用于处理和操作文本数据,提供了丰富的字符串处理方法。
字符串基本操作:
const str = "Hello, World!";// 字符串长度
console.log(str.length); // 13// 访问字符
console.log(str[0]); // 'H'
console.log(str.charAt(4)); // 'o'// 字符串拼接
const firstName = "John";
const lastName = "Doe";
console.log(firstName + " " + lastName); // "John Doe"
console.log(`${firstName} ${lastName}`); // 模板字符串: "John Doe"
字符串查找与比较:
const str = "Hello, World!";// 查找子字符串
console.log(str.indexOf("World")); // 7 (第一次出现的位置)
console.log(str.lastIndexOf("o")); // 8 (最后一次出现的位置)
console.log(str.includes("Hello")); // true (是否包含子字符串)
console.log(str.startsWith("Hello")); // true (是否以...开头)
console.log(str.endsWith("!")); // true (是否以...结尾)// 比较字符串
const str1 = "apple";
const str2 = "banana";
console.log(str1.localeCompare(str2)); // -1 (按字母表顺序比较)
字符串修改与转换:
const str = " Hello, World! ";// 大小写转换
console.log(str.toUpperCase()); // " HELLO, WORLD! "
console.log(str.toLowerCase()); // " hello, world! "// 去除空白
console.log(str.trim()); // "Hello, World!"// 替换子字符串
console.log(str.replace("World", "JavaScript")); // " Hello, JavaScript! "// 分割字符串
const fruits = "apple,banana,orange";
console.log(fruits.split(",")); // ["apple", "banana", "orange"]// 重复字符串
console.log("abc".repeat(3)); // "abcabcabc"
字符串提取与切片:
const str = "Hello, World!";// 提取子字符串
console.log(str.substring(7, 12)); // "World" (从索引7到12,但不包含12)
console.log(str.substr(7, 5)); // "World" (从索引7开始,长度为5)
console.log(str.slice(7, 12)); // "World" (类似substring,但支持负数索引)
console.log(str.slice(-6, -1)); // "World" (负数索引从后往前数)
综合案例:字符串加密与解密
// 简单的凯撒密码加密
function encrypt(text, shift) {return text.split('').map(char => {const code = char.charCodeAt(0);if (code >= 65 && code <= 90) {return String.fromCharCode(((code - 65 + shift) % 26) + 65);} else if (code >= 97 && code <= 122) {return String.fromCharCode(((code - 97 + shift) % 26) + 97);}return char;}).join('');
}// 解密函数
function decrypt(text, shift) {return encrypt(text, 26 - shift); // 解密就是反向移位
}const message = "Hello, World!";
const encrypted = encrypt(message, 3);
const decrypted = decrypt(encrypted, 3);console.log(encrypted); // "Khoor, Zruog!"
console.log(decrypted); // "Hello, World!"
四、综合应用案例:生日计算器
结合上述三个对象,我们可以创建一个实用的生日计算器,它能计算用户的年龄、下一个生日还有多久,并生成个性化的生日祝福。
// 生日计算器
function birthdayCalculator(birthdayStr) {// 解析生日const [year, month, day] = birthdayStr.split('-').map(Number);const birthday = new Date(year, month - 1, day);// 计算年龄const today = new Date();let age = today.getFullYear() - birthday.getFullYear();const monthDiff = today.getMonth() - birthday.getMonth();if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthday.getDate())) {age--;}// 计算下一个生日let nextBirthday = new Date(today.getFullYear(), birthday.getMonth(), birthday.getDate());if (nextBirthday < today) {nextBirthday.setFullYear(nextBirthday.getFullYear() + 1);}// 计算距离下一个生日的天数const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数const daysUntilBirthday = Math.ceil((nextBirthday - today) / oneDay);// 生成随机祝福消息const messages = ["生日快乐!愿你的新一岁充满无限可能!","又长了一岁,愿你越来越成熟,越来越优秀!","新的一岁,愿你的生活如彩虹般绚丽多彩!","生日快乐!愿你的梦想都能成真!"];const randomIndex = Math.floor(Math.random() * messages.length);const birthdayMessage = messages[randomIndex];return {age,daysUntilBirthday,birthdayMessage,formattedBirthday: birthday.toLocaleDateString(),formattedNextBirthday: nextBirthday.toLocaleDateString()};
}// 使用示例
const result = birthdayCalculator("1990-05-15");
console.log(`你出生于: ${result.formattedBirthday}`);
console.log(`你现在 ${result.age} 岁`);
console.log(`距离你下次生日还有 ${result.daysUntilBirthday} 天`);
console.log(`生日祝福: ${result.birthdayMessage}`);
总结
通过本文的介绍,我们深入了解了 JavaScript 中三个重要的内置对象:Math、Date 和 String。掌握这些对象的用法,能让你在处理数值计算、时间操作和文本处理时更加得心应手。在实际开发中,这些对象的方法往往会结合使用,帮助你构建出更强大、更高效的应用程序。希望本文的内容对你的 JavaScript 学习和开发有所帮助!