【前端开发】四. JS内置函数

发布于:2025-08-11 ⋅ 阅读:(16) ⋅ 点赞:(0)

JavaScript 内置函数全面指南

一、全局函数

1. 类型转换函数

// 转换为数字
console.log(Number("42"));      // 42
console.log(parseInt("100px")); // 100
console.log(parseFloat("3.14")); // 3.14

// 转换为字符串
console.log(String(123));       // "123"
console.log((42).toString());   // "42"

// 转换为布尔值
console.log(Boolean(1));        // true
console.log(Boolean(0));        // false

2. 编码解码函数

// URI 编码
const uri = "https://example.com/测试页面";
console.log(encodeURI(uri));       // "https://example.com/%E6%B5%8B%E8%AF%95%E9%A1%B5%E9%9D%A2"
console.log(encodeURIComponent(uri)); // "https%3A%2F%2Fexample.com%2F%E6%B5%8B%E8%AF%95%E9%A1%B5%E9%9D%A2"

// URI 解码
const encoded = "https%3A%2F%2Fexample.com%2Fpage%3Fq%3D%E6%B5%8B%E8%AF%95";
console.log(decodeURI(encoded));       // "https://example.com/page?q=测试"
console.log(decodeURIComponent(encoded)); // "https://example.com/page?q=测试"

3. 数值处理函数

// 检查有限数
console.log(isFinite(123));      // true
console.log(isFinite(Infinity)); // false

// 检查 NaN
console.log(isNaN(123));         // fal
console.log(isNaN("abc"));       // true

// 浮点数解析
console.log(parseFloat("3.14abc")); // 3.14
console.log(parseInt("1010", 2));   // 10 (二进制解析)

二、数组方法

1. 基本操作方法

const fruits = ["Apple", "Banana"];

// 添加/删除元素
fruits.push("Orange");       // 末尾添加
fruits.pop();                // 末尾删除
fruits.unshift("Mango");     // 开头添加
fruits.shift();              // 开头删除

// 修改数组
fruits.splice(1, 0, "Kiwi"); // 在索引1处插入"Kiwi"
fruits.splice(1, 1);         // 删除索引1的元素

// 合并数组
const moreFruits = ["Grape", "Pineapple"];
const allFruits = fruits.concat(moreFruits);

2. 遍历方法

const numbers = [1, 2, 3, 4, 5];

// forEach - 遍历元素
numbers.forEach((num, index) => {
  console.log(`Index ${index}: ${num}`);
});

// map - 转换数组
const squared = numbers.map(num => num * num); // [1, 4, 9, 16, 25]

// filter - 过滤元素
const evenNumbers = numbers.filter(num => num % 2 === 0); // [2, 4]

// reduce - 累积计算
const sum = numbers.reduce((acc, num) => acc + num, 0); // 15

// find/findIndex - 查找元素
const firstEven = numbers.find(num => num % 2 === 0); // 2
const firstEvenIndex = numbers.findIndex(num => num % 2 === 0); // 1

3. 排序和搜索

const scores = [95, 78, 85, 60, 92];

// 排序
scores.sort((a, b) => a - b); // [60, 78, 85, 92, 95]

// 反转
scores.reverse(); // [95, 92, 85, 78, 60]

// 搜索
console.log(scores.includes(85)); // true
console.log(scores.indexOf(92));  // 1
console.log(scores.lastIndexOf(95)); // 0

// 检查条件
console.log(scores.every(score => score > 50)); // true
console.log(scores.some(score => score > 90));  // true

三、字符串方法

1. 基本操作方法

const text = "JavaScript is awesome!";

// 获取长度
console.log(text.length); // 23

// 获取字符
console.log(text.charAt(4));     // 'S'
console.log(text[4]);            // 'S' (类似数组访问)
console.log(text.charCodeAt(0)); // 74 (J的Unicode)

// 提取子串
console.log(text.substring(0, 10)); // "JavaScript"
console.log(text.slice(-9));        // "awesome!"
console.log(text.substr(11, 2));    // "is"

// 大小写转换
console.log(text.toUpperCase()); // "JAVASCRIPT IS AWESOME!"
console.log(text.toLowerCase()); // "javascript is awesome!"

2. 搜索和替换

const message = "Hello, world! Welcome to JavaScript world.";

// 搜索
console.log(message.indexOf("world"));      // 7
console.log(message.lastIndexOf("world"));  // 32
console.log(message.includes("JavaScript")); // true
console.log(message.startsWith("Hello"));    // true
console.log(message.endsWith("world."));     // true

// 替换
console.log(message.replace("world", "Earth")); 
// "Hello, Earth! Welcome to JavaScript world."

// 全局替换
console.log(message.replace(/world/g, "Earth"));
// "Hello, Earth! Welcome to JavaScript Earth."

// 正则表达式匹配
const matches = message.match(/[A-Z]\w+/g);
console.log(matches); // ["Hello", "Welcome", "JavaScript"]

3. 字符串分割和清理

const csv = "apple,banana,orange,grape";

// 分割字符串
const fruits = csv.split(","); 
// ["apple", "banana", "orange", "grape"]

// 连接字符串
const newText = fruits.join("; ");
// "apple; banana; orange; grape"

// 清理字符串
const dirtyText = "   Some text with spaces   ";
console.log(dirtyText.trim());      // "Some text with spaces"
console.log(dirtyText.trimStart()); // "Some text with spaces   "
console.log(dirtyText.trimEnd());   // "   Some text with spaces"

四、对象方法

1. 对象属性操作

const person = {
  name: "Alice",
  age: 30,
  job: "Developer"
};

// 获取键/值/条目
console.log(Object.keys(person));    // ["name", "age", "job"]
console.log(Object.values(person));  // ["Alice", 30, "Developer"]
console.log(Object.entries(person)); 
// [["name", "Alice"], ["age", 30], ["job", "Developer"]]

// 合并对象
const details = { city: "New York", country: "USA" };
const fullPerson = Object.assign({}, person, details);

// 冻结对象
Object.freeze(fullPerson); // 防止修改
fullPerson.age = 31; // 无效(严格模式下报错)

2. 原型和属性描述

// 创建对象
const car = Object.create({ 
  start() { console.log("Engine started!"); }
});

// 添加属性
Object.defineProperty(car, "brand", {
  value: "Toyota",
  writable: false, // 不可修改
  enumerable: true // 可枚举
});

// 获取属性描述符
console.log(Object.getOwnPropertyDescriptor(car, "brand"));

// 设置原型
const electricCar = { battery: "100kWh" };
Object.setPrototypeOf(electricCar, car);
electricCar.start(); // "Engine started!"

五、数学函数 (Math 对象)

1. 基本数学运算

// 常用常数
console.log(Math.PI);        // 3.141592653589793
console.log(Math.E);         // 2.718281828459045

// 取整方法
console.log(Math.round(3.6)); // 4
console.log(Math.floor(3.6)); // 3
console.log(Math.ceil(3.2));  // 4
console.log(Math.trunc(3.9)); // 3 (移除小数部分)

// 绝对值
console.log(Math.abs(-5));   // 5

// 幂和根
console.log(Math.pow(2, 8)); // 256
console.log(Math.sqrt(64));  // 8
console.log(Math.cbrt(27));  // 3 (立方根)

2. 随机数和最值

// 随机数
console.log(Math.random()); // 0~1之间的随机数

// 生成范围随机整数
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomInt(10, 20)); // 10~20之间的整数

// 最值
console.log(Math.max(10, 20, 5, 30)); // 30
console.log(Math.min(10, 20, 5, 30)); // 5

// 数组中的最值
const nums = [4, 2, 9, 5];
console.log(Math.max(...nums)); // 9

六、日期函数 (Date 对象)

1. 创建和获取日期

// 创建日期
const now = new Date();
const specificDate = new Date(2023, 5, 15, 10, 30); // 月份0-11
const isoDate = new Date("2023-06-15T10:30:00Z");

// 获取日期组件
console.log(now.getFullYear());    // 当前年份
console.log(now.getMonth());       // 当前月份 (0-11)
console.log(now.getDate());        // 当前日 (1-31)
console.log(now.getDay());         // 星期几 (0-6, 0=周日)
console.log(now.getHours());       // 小时 (0-23)
console.log(now.getMinutes());     // 分钟 (0-59)
console.log(now.getSeconds());     // 秒 (0-59)
console.log(now.getMilliseconds());// 毫秒 (0-999)
console.log(now.getTime());        // 时间戳 (毫秒数)

// UTC 方法
console.log(now.getUTCHours());    // UTC小时

2. 设置和格式化日期

const date = new Date();

// 设置日期
date.setFullYear(2024);
date.setMonth(11); // 12月
date.setDate(25);
date.setHours(15);
date.setMinutes(45);

// 日期计算
date.setDate(date.getDate() + 7); // 加7天

// 格式化
console.log(date.toISOString());      // "2024-12-25T15:45:00.000Z"
console.log(date.toLocaleDateString()); // 本地格式日期
console.log(date.toLocaleTimeString()); // 本地格式时间

// 自定义格式化
function formatDate(date) {
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
}
console.log(formatDate(date)); // "2024-12-25"

七、JSON 方法

1. JSON 序列化和解析

const person = {
  name: "Bob",
  age: 35,
  hobbies: ["reading", "hiking"],
  isAdmin: true,
  birthDate: new Date()
};

// 序列化为 JSON 字符串
const jsonString = JSON.stringify(person);
console.log(jsonString);
// {"name":"Bob","age":35,"hobbies":["reading","hiking"],"isAdmin":true,"birthDate":"2023-07-25T12:00:00.000Z"}

// 解析 JSON 字符串
const parsedPerson = JSON.parse(jsonString);
console.log(parsedPerson.name); // "Bob"

// 使用 reviver 函数
const revivedPerson = JSON.parse(jsonString, (key, value) => {
  if (key === "birthDate") return new Date(value);
  return value;
});
console.log(revivedPerson.birthDate.getFullYear()); // 2023

2. 高级序列化选项

// 过滤属性
console.log(JSON.stringify(person, ["name", "age"]));
// {"name":"Bob","age":35}

// 自定义序列化
console.log(JSON.stringify(person, (key, value) => {
  if (typeof value === "string") return value.toUpperCase();
  return value;
}));
// {"name":"BOB","age":35,"hobbies":["READING","HIKING"],"isAdmin":true,"birthDate":"2023-07-25T12:00:00.000Z"}

// 格式化输出
console.log(JSON.stringify(person, null, 2));
/*
{
  "name": "Bob",
  "age": 35,
  "hobbies": [
    "reading",
    "hiking"
  ],
  "isAdmin": true,
  "birthDate": "2023-07-25T12:00:00.000Z"
}
*/

八、其他实用内置函数

1. 定时器函数

// 延迟执行
setTimeout(() => {
  console.log("This runs after 2 seconds");
}, 2000);

// 定期执行
let counter = 0;
const intervalId = setInterval(() => {
  console.log(`Counter: ${++counter}`);
  if (counter >= 5) clearInterval(intervalId);
}, 1000);

// 立即执行(当前事件循环结束后)
setImmediate(() => {
  console.log("This runs immediately after the current operation");
});

// 下一帧执行
requestAnimationFrame(() => {
  console.log("Runs before the next repaint");
});

2. 错误处理函数

// 抛出错误
function divide(a, b) {
  if (b === 0) throw new Error("Division by zero");
  return a / b;
}

// 捕获错误
try {
  const result = divide(10, 0);
  console.log(result);
} catch (error) {
  console.error("Error occurred:", error.message);
} finally {
  console.log("This always runs");
}

// 创建错误对象
const customError = new Error("Custom error");
customError.code = 500;
console.log(customError.stack); // 错误堆栈

3. Promise 相关函数

// 创建 Promise
const fetchData = () => new Promise((resolve, reject) => {
  setTimeout(() => {
    Math.random() > 0.5 
      ? resolve("Data received") 
      : reject(new Error("Request failed"));
  }, 1000);
});

// 使用 Promise
fetchData()
  .then(data => console.log(data))
  .catch(err => console.error(err));

// Promise 工具方法
const promises = [
  Promise.resolve(1),
  Promise.resolve(2),
  Promise.reject(new Error("Failed"))
];

Promise.all(promises) // 全部成功
  .catch(err => console.log("All failed:", err));

Promise.allSettled(promises) // 全部完成
  .then(results => console.log(results));

Promise.race(promises) // 第一个完成
  .then(result => console.log("First:", result));

Promise.any(promises) // 第一个成功
  .then(result => console.log("First success:", result));

九、最佳实践与性能技巧

1. 函数选择指南

场景

推荐函数

原因

数组遍历

forEach/map

简洁、函数式编程

数组过滤

filter

可读性强

数组搜索

find/findIndex

优于循环+break

对象复制

Object.assign/展开运算符

避免引用问题

深度复制

JSON.parse(JSON.stringify())

简单有效

异步操作

async/await

优于回调/Promise链

2. 性能优化技巧

// 1. 避免在循环中创建函数
// 差
for (let i = 0; i < 1000; i++) {
  element.addEventListener('click', () => doSomething(i));
}

// 优
function createHandler(i) {
  return () => doSomething(i);
}
for (let i = 0; i < 1000; i++) {
  element.addEventListener('click', createHandler(i));
}

// 2. 使用 Map 替代对象存储键值对(大量数据时)
const largeDataMap = new Map();
for (let i = 0; i < 100000; i++) {
  largeDataMap.set(`key${i}`, i);
}

// 3. 使用 DocumentFragment 进行批量 DOM 操作
const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
  const div = document.createElement('div');
  div.textContent = `Item ${i}`;
  fragment.appendChild(div);
}
document.body.appendChild(fragment);

// 4. 使用 Web Workers 处理 CPU 密集型任务
const worker = new Worker('worker.js');
worker.postMessage({ data: largeArray });
worker.onmessage = (event) => {
  console.log('Result:', event.data);
};

十、实战应用示例

1. 数据格式转换

// API 响应数据转换
const apiResponse = {
  data: {
    users: [
      { id: 1, name: "Alice", age: 30 },
      { id: 2, name: "Bob", age: 25 }
    ],
    meta: {
      page: 1,
      totalPages: 5
    }
  }
};

// 转换为更简洁格式
const normalizedData = {
  users: apiResponse.data.users.map(user => ({
    ...user,
    fullName: `${user.name} (ID: ${user.id})`
  })),
  pagination: apiResponse.data.meta
};

console.log(normalizedData);

2. 用户输入验证

function validateForm(formData) {
  const errors = {};
  
  // 验证用户名
  if (!formData.username) {
    errors.username = "用户名不能为空";
  } else if (formData.username.length < 3) {
    errors.username = "用户名至少3个字符";
  }
  
  // 验证邮箱
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(formData.email)) {
    errors.email = "邮箱格式不正确";
  }
  
  // 验证密码
  if (formData.password.length < 8) {
    errors.password = "密码至少8个字符";
  } else if (formData.password !== formData.confirmPassword) {
    errors.confirmPassword = "两次密码输入不一致";
  }
  
  return Object.keys(errors).length === 0 ? null : errors;
}

const formData = {
  username: "al",
  email: "invalid-email",
  password: "1234567",
  confirmPassword: "12345678"
};

console.log(validateForm(formData));
/*
{
  username: "用户名至少3个字符",
  email: "邮箱格式不正确",
  password: "密码至少8个字符",
  confirmPassword: "两次密码输入不一致"
}
*/

3. 日期处理工具

class DateUtils {
  static format(date, format = "YYYY-MM-DD") {
    const pad = num => num.toString().padStart(2, '0');
    
    return format
      .replace(/YYYY/g, date.getFullYear())
      .replace(/MM/g, pad(date.getMonth() + 1))
      .replace(/DD/g, pad(date.getDate()))
      .replace(/HH/g, pad(date.getHours()))
      .replace(/mm/g, pad(date.getMinutes()))
      .replace(/ss/g, pad(date.getSeconds()));
  }
  
  static addDays(date, days) {
    const result = new Date(date);
    result.setDate(result.getDate() + days);
    return result;
  }
  
  static differenceInDays(date1, date2) {
    const diffTime = Math.abs(date2 - date1);
    return Math.floor(diffTime / (1000 * 60 * 60 * 24));
  }
}

const today = new Date();
console.log(DateUtils.format(today)); // "2023-07-25"
console.log(DateUtils.format(today, "YYYY/MM/DD HH:mm:ss")); // "2023/07/25 12:30:45"

const nextWeek = DateUtils.addDays(today, 7);
console.log(DateUtils.differenceInDays(today, nextWeek)); // 7