JavaScript 常用 API
JavaScript 提供了丰富的内置 API,下面分类介绍一些最常用的 API:
数组操作 API
// 创建数组
const arr = [1, 2, 3];
const arr2 = new Array(5).fill(0);
// 常用方法
arr.push(4); // 末尾添加
arr.pop(); // 移除末尾
arr.shift(); // 移除开头
arr.unshift(0); // 开头添加
arr.concat([4,5]); // 合并数组
arr.slice(1,3); // 截取
arr.splice(1,1,'a','b'); // 删除/替换
// 遍历
arr.forEach(item => console.log(item));
const mapped = arr.map(item => item * 2);
const filtered = arr.filter(item => item > 1);
const reduced = arr.reduce((acc, cur) => acc + cur, 0);
// 查找
arr.includes(2); // true
arr.indexOf(2); // 1
arr.find(item => item > 1); // 2
arr.findIndex(item => item > 1); // 1
// 其他
arr.sort((a,b) => a - b);//排序,b-a为倒叙
arr.reverse(); //反转数组顺序
arr.every(item => item > 0); // 所有满足
arr.some(item => item > 2); // 至少一个满足
字符串操作 API
const str = "Hello World";
// 常用方法
str.length; // 11
str.charAt(1); // 'e'
str.substring(1,4); // 'ell'
str.slice(1,4); // 'ell'
str.split(' '); // ['Hello', 'World']
str.replace('World', 'JS'); // 'Hello JS'
str.toLowerCase(); // 'hello world'
str.toUpperCase(); // 'HELLO WORLD'
str.trim(); // 去首尾空格
// 查找
str.indexOf('l'); // 2
str.lastIndexOf('l'); // 9
str.includes('World'); // true
str.startsWith('Hello'); // true
str.endsWith('ld'); // true
// ES6+
str.repeat(2); // 'Hello WorldHello World'
str.padStart(15, '*'); // '****Hello World'
对象操作 API
const obj = { a: 1, b: 2, c: 3 };
// 常用方法
Object.keys(obj); // ['a', 'b', 'c']
Object.values(obj); // [1, 2, 3]
Object.entries(obj); // [['a',1], ['b',2], ['c',3]]
Object.assign({}, obj, { d:4 }); // 合并对象
Object.freeze(obj); // 冻结对象
Object.seal(obj); // 密封对象
// ES6+
const { a, ...rest } = obj; // 解构
const newObj = { ...obj, d:4 }; // 扩展运算符
日期操作 API
const now = new Date();
// 常用方法
now.getFullYear(); // 年
now.getMonth(); // 月 (0-11)
now.getDate(); // 日
now.getDay(); // 星期 (0-6)
now.getHours(); // 时
now.getMinutes(); // 分
now.getSeconds(); // 秒
now.getTime(); // 时间戳
// 设置
now.setFullYear(2023);
now.setMonth(11); // 12月
// 格式化
now.toISOString(); // "2023-12-31T16:00:00.000Z"
now.toLocaleString(); // 本地格式
数学运算 API
Math.PI; // 圆周率
Math.abs(-5); // 5
Math.ceil(4.1); // 5
Math.floor(4.9); // 4
Math.round(4.5); // 5
Math.max(1,2,3); // 3
Math.min(1,2,3); // 1
Math.random(); // 0-1随机数
Math.sqrt(9); // 3
Math.pow(2,3); // 8
Math.sin(Math.PI/2); // 1
异步操作 API
// Promise
new Promise((resolve, reject) => {
setTimeout(() => resolve('成功'), 1000);
}).then(result => console.log(result));
// async/await
async function fetchData() {
const response = await fetch('api/data');
const data = await response.json();
return data;
}
// Fetch API
fetch('api/data')
.then(response => response.json())
.then(data => console.log(data));
// setTimeout / setInterval
setTimeout(() => console.log('延迟执行'), 1000);
const timer = setInterval(() => console.log('间隔执行'), 1000);
clearInterval(timer); // 清除
浏览器相关 API
// DOM 操作
document.getElementById('id');
document.querySelector('.class');
document.querySelectorAll('div');
element.innerHTML = '新内容';
element.style.color = 'red';
element.classList.add('active');
element.addEventListener('click', handler);
// 存储
localStorage.setItem('key', 'value');
sessionStorage.getItem('key');
// 浏览器信息
window.innerWidth; // 视口宽度
window.location.href; // 当前URL
window.history.back(); // 后退
navigator.userAgent; // 用户代理
// 事件
window.addEventListener('resize', handleResize);
document.addEventListener('DOMContentLoaded', init);
ES6+ 新增常用 API
// Map/Set
const map = new Map();
map.set('key', 'value');
map.get('key'); //进行查找是否含有,含有返回true
const set = new Set([1,2,3]);
set.add(4); //在set中添加
set.has(2); //进行查找是否含有,含有返回true
// 类型数组
const buffer = new ArrayBuffer(16);
const int32View = new Int32Array(buffer);
// 其他
Symbol('description');
BigInt(9007199254740991);
// 对象增强
Object.fromEntries([['a',1], ['b',2]]);
Object.hasOwn(obj, 'a'); // 替代 obj.hasOwnProperty
这些是 JavaScript 中最常用的 API,掌握它们可以应对大多数开发需求。根据不同的应用场景(如 Node.js、浏览器环境等),还会有更多特定的 API 可供使用。