Appearance
JavaScript 速查表
JavaScript速查表提供了常用语法、方法和技巧的快速参考,帮助开发者快速查找和使用JavaScript特性。
基础语法
变量声明
javascript
// var - 函数作用域(不推荐使用)
var name = 'John';
// let - 块级作用域,可重新赋值
let age = 30;
age = 31; // 有效
// const - 块级作用域,不可重新赋值
const PI = 3.14159;
// PI = 3.14; // 错误!
// const对象/数组可以修改内容
const obj = { name: 'John' };
obj.name = 'Jane'; // 有效
obj.age = 30; // 有效
// obj = {}; // 错误!
数据类型
javascript
// 原始类型
typeof 'hello'; // 'string'
typeof 42; // 'number'
typeof true; // 'boolean'
typeof undefined; // 'undefined'
typeof Symbol(); // 'symbol'
typeof 123n; // 'bigint'
typeof null; // 'object' (历史bug)
// 对象类型
typeof {}; // 'object'
typeof []; // 'object'
typeof function() {}; // 'function'
运算符
javascript
// 算术运算符
+ // 加法
- // 减法
* // 乘法
/ // 除法
% // 取模
** // 幂运算
// 比较运算符
== // 相等(类型转换)
=== // 严格相等(不转换类型)
!= // 不等
!== // 严格不等
> // 大于
< // 小于
>= // 大于等于
<= // 小于等于
// 逻辑运算符
&& // 逻辑与
|| // 逻辑或
! // 逻辑非
// 赋值运算符
= // 赋值
+= // 加法赋值
-= // 减法赋值
*= // 乘法赋值
/= // 除法赋值
%= // 取模赋值
// 三元运算符
condition ? value1 : value2
// 空值合并运算符 (ES2020)
a ?? b // 只有当a为null或undefined时返回b
// 逻辑赋值运算符 (ES2021)
a &&= b; // a && (a = b)
a ||= b; // a || (a = b)
a ??= b; // a ?? (a = b)
函数
函数定义
javascript
// 函数声明
function greet(name) {
return `Hello, ${name}!`;
}
// 函数表达式
const greet = function(name) {
return `Hello, ${name}!`;
};
// 箭头函数
const greet = (name) => `Hello, ${name}!`;
const square = x => x * x; // 单参数可省略括号
const getRandom = () => Math.random(); // 无参数需括号
const add = (a, b) => { // 多行需大括号和return
return a + b;
};
// 参数默认值
function greet(name = 'World', punctuation = '!') {
return `Hello, ${name}${punctuation}`;
}
// 剩余参数
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
数组方法
遍历方法
javascript
const numbers = [1, 2, 3, 4, 5];
// forEach - 遍历数组
numbers.forEach((num, index) => console.log(num, index));
// map - 转换数组
const doubled = numbers.map(num => num * 2); // [2, 4, 6, 8, 10]
// filter - 过滤元素
const evens = numbers.filter(num => num % 2 === 0); // [2, 4]
// find - 查找第一个匹配项
const found = numbers.find(num => num > 3); // 4
// findIndex - 查找第一个匹配项的索引
const index = numbers.findIndex(num => num === 4); // 3
归约方法
javascript
const numbers = [1, 2, 3, 4, 5];
// reduce - 归约操作
const sum = numbers.reduce((acc, curr) => acc + curr, 0); // 15
const product = numbers.reduce((acc, curr) => acc * curr, 1); // 120
// reduceRight - 从右到左归约
const rightSum = numbers.reduceRight((acc, curr) => acc + curr, 0);
搜索方法
javascript
const arr = [1, 2, 3, 4, 5];
// includes - 检查是否包含元素
arr.includes(3); // true
// indexOf - 查找元素索引
arr.indexOf(3); // 2
// lastIndexOf - 从后往前查找
arr.lastIndexOf(3); // 2
数组转换
javascript
const arr = [1, 2, 3, 4, 5];
// slice - 提取子数组(不修改原数组)
const sub = arr.slice(1, 4); // [2, 3, 4]
// concat - 合并数组(不修改原数组)
const combined = arr.concat([6, 7]); // [1, 2, 3, 4, 5, 6, 7]
// flat - 数组扁平化
const nested = [1, [2, 3], [4, [5, 6]]];
nested.flat(); // [1, 2, 3, 4, [5, 6]]
nested.flat(2); // [1, 2, 3, 4, 5, 6]
nested.flat(Infinity); // [1, 2, 3, 4, 5, 6]
// flatMap - map + flat
const result = [1, 2, 3].flatMap(x => [x, x * 2]); // [1, 2, 2, 4, 3, 6]
数组变异方法
javascript
const arr = [1, 2, 3];
// push/pop - 末尾添加/移除
arr.push(4); // [1, 2, 3, 4]
arr.pop(); // [1, 2, 3]
// unshift/shift - 开头添加/移除
arr.unshift(0); // [0, 1, 2, 3]
arr.shift(); // [1, 2, 3]
// splice - 添加/删除/替换元素
arr.splice(1, 1, 'a', 'b'); // 从索引1开始删除1个元素,插入'a'和'b'
// reverse - 反转数组
arr.reverse(); // 修改原数组
// sort - 排序
arr.sort(); // 按字符串排序
arr.sort((a, b) => a - b); // 数字升序
arr.sort((a, b) => b - a); // 数字降序
对象操作
对象创建和访问
javascript
// 对象字面量
const person = {
name: 'John',
age: 30,
greet() {
return `Hello, I'm ${this.name}`;
}
};
// 访问属性
person.name; // 点表示法
person['name']; // 括号表示法
person[expr]; // 计算属性名
// 解构赋值
const { name, age } = person;
const { name: personName, age: personAge } = person; // 重命名
const { name, country = 'USA' } = person; // 默认值
// 嵌套解构
const user = {
name: 'John',
address: { city: 'NYC', zip: '10001' }
};
const { address: { city, zip } } = user;
对象方法
javascript
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]]
// 对象遍历
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key, obj[key]);
}
}
// 检查属性
obj.hasOwnProperty('a'); // true
'a' in obj; // true
Object.hasOwn(obj, 'a'); // true (ES2022)
// 对象合并
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const merged = { ...obj1, ...obj2 }; // 扩展运算符
const merged2 = Object.assign({}, obj1, obj2); // Object.assign
对象属性描述符
javascript
const obj = {};
// 定义属性描述符
Object.defineProperty(obj, 'name', {
value: 'John',
writable: true, // 是否可修改
enumerable: true, // 是否可枚举
configurable: true // 是否可配置
});
// 获取属性描述符
const descriptor = Object.getOwnPropertyDescriptor(obj, 'name');
// 定义多个属性
Object.defineProperties(obj, {
name: { value: 'John', writable: true },
age: { value: 30, writable: true }
});
字符串操作
常用字符串方法
javascript
const str = 'Hello World';
// 基本操作
str.length; // 11
str.charAt(0); // 'H'
str[0]; // 'H'
str.indexOf('World'); // 6
str.includes('World'); // true
str.startsWith('Hello'); // true
str.endsWith('World'); // true
// 转换方法
str.toUpperCase(); // 'HELLO WORLD'
str.toLowerCase(); // 'hello world'
str.trim(); // 去除首尾空格
str.trimStart(); // 去除开头空格
str.trimEnd(); // 去除结尾空格
// 截取方法
str.slice(0, 5); // 'Hello'
str.substring(0, 5); // 'Hello'
str.substr(0, 5); // 'Hello' (已废弃)
// 分割和连接
str.split(' '); // ['Hello', 'World']
'Hello'.concat(' ', 'World'); // 'Hello World'
'Hello' + ' ' + 'World'; // 'Hello World'
// 模板字符串
const name = 'John';
const greeting = `Hello, ${name}!`; // 'Hello, John!'
条件和循环
条件语句
javascript
// if-else
if (condition) {
// 代码块
} else if (anotherCondition) {
// 代码块
} else {
// 代码块
}
// switch
switch (expression) {
case value1:
// 代码块
break;
case value2:
// 代码块
break;
default:
// 代码块
}
// 三元运算符
const result = condition ? value1 : value2;
// 短路求值
const result = obj && obj.property; // 防止空指针错误
const defaultValue = value || 'default'; // 设置默认值
const fallbackValue = value ?? 'fallback'; // 只有null/undefined时使用默认值
循环语句
javascript
// for循环
for (let i = 0; i < 10; i++) {
console.log(i);
}
// while循环
let count = 0;
while (count < 5) {
console.log(count);
count++;
}
// do-while循环
let index = 0;
do {
console.log(index);
index++;
} while (index < 5);
// for...of - 遍历可迭代对象
const arr = [1, 2, 3];
for (const item of arr) {
console.log(item);
}
// for...in - 遍历对象的可枚举属性
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key, obj[key]);
}
}
异步编程
Promise
javascript
// 创建Promise
const promise = new Promise((resolve, reject) => {
// 异步操作
setTimeout(() => {
const success = Math.random() > 0.5;
if (success) {
resolve('成功');
} else {
reject(new Error('失败'));
}
}, 1000);
});
// 使用Promise
promise
.then(result => console.log(result))
.catch(error => console.error(error))
.finally(() => console.log('完成'));
// Promise静态方法
Promise.resolve('resolved'); // 已解决的Promise
Promise.reject('rejected'); // 已拒绝的Promise
Promise.all([p1, p2, p3]); // 所有都成功才成功
Promise.allSettled([p1, p2]); // 等待所有完成
Promise.race([p1, p2, p3]); // 第一个完成的决定结果
async/await
javascript
// async函数
async function fetchData() {
try {
const response = await fetch('/api/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
throw error;
}
}
// 并行执行
async function fetchMultiple() {
const [users, posts, comments] = await Promise.all([
fetch('/api/users').then(r => r.json()),
fetch('/api/posts').then(r => r.json()),
fetch('/api/comments').then(r => r.json())
]);
return { users, posts, comments };
}
DOM 操作
元素选择
javascript
// 通过ID获取
const element = document.getElementById('myId');
// 通过类名获取
const elements = document.getElementsByClassName('myClass');
// 通过标签名获取
const divs = document.getElementsByTagName('div');
// 通过CSS选择器获取
const header = document.querySelector('.header'); // 第一个匹配
const buttons = document.querySelectorAll('button'); // 所有匹配
// 选择器语法示例
document.querySelector('#id'); // ID选择器
document.querySelector('.class'); // 类选择器
document.querySelector('div'); // 标签选择器
document.querySelector('[data-id]'); // 属性选择器
document.querySelector('div > p'); // 子元素选择器
document.querySelector('div p'); // 后代选择器
元素操作
javascript
const element = document.querySelector('.myElement');
// 内容操作
element.textContent = '新文本内容';
element.innerHTML = '<strong>新HTML内容</strong>';
// 属性操作
element.getAttribute('src');
element.setAttribute('src', 'new-image.jpg');
element.removeAttribute('alt');
// class操作
element.classList.add('new-class');
element.classList.remove('old-class');
element.classList.toggle('active');
element.classList.contains('active');
// 样式操作
element.style.color = 'red';
element.style.cssText = 'color: red; background: blue;';
Object.assign(element.style, { color: 'green', fontSize: '16px' });
// 创建和插入元素
const newElement = document.createElement('div');
newElement.textContent = '新元素';
document.body.appendChild(newElement);
// 使用文档片段提高性能
const fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
const li = document.createElement('li');
li.textContent = `Item ${i}`;
fragment.appendChild(li);
}
document.querySelector('#list').appendChild(fragment);
事件处理
javascript
const button = document.querySelector('#myButton');
// 添加事件监听器
button.addEventListener('click', function(event) {
console.log('按钮被点击');
console.log('事件对象:', event);
});
// 事件对象常用属性
event.type; // 事件类型
event.target; // 触发事件的元素
event.currentTarget; // 当前处理事件的元素
event.preventDefault(); // 阻止默认行为
event.stopPropagation(); // 阻止事件冒泡
// 事件委托
document.addEventListener('click', function(event) {
if (event.target.matches('.button')) {
console.log('按钮被点击');
}
});
// 事件选项
element.addEventListener('click', handler, {
once: true, // 只执行一次
passive: true, // 被动模式
capture: true // 捕获阶段
});
错误处理
try-catch-finally
javascript
try {
// 可能出错的代码
const result = riskyOperation();
console.log(result);
} catch (error) {
// 错误处理
console.error('发生错误:', error.message);
} finally {
// 无论是否有错误都会执行
console.log('清理工作');
}
// 自定义错误类型
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}
常见错误类型
javascript
// TypeError - 类型错误
null.someMethod(); // Cannot read property 'someMethod' of null
// ReferenceError - 引用错误
console.log(undefinedVariable); // undefinedVariable is not defined
// SyntaxError - 语法错误(通常在代码解析阶段)
// const invalidSyntax = ; // Unexpected token ';'
// RangeError - 范围错误
new Array(-1); // Invalid array length
ES6+ 新特性
模板字符串
javascript
const name = 'John';
const age = 30;
// 基本用法
const greeting = `Hello, ${name}! You are ${age} years old.`;
// 多行字符串
const multiline = `
这是
多行
字符串
`;
// 标签模板
function highlight(strings, ...values) {
return strings.reduce((result, string, i) => {
const value = values[i] ? `<mark>${values[i]}</mark>` : '';
return result + string + value;
}, '');
}
解构赋值
javascript
// 数组解构
const [first, second, third] = [1, 2, 3];
const [a, , c] = [1, 2, 3]; // 跳过第二个元素
const [x, y, ...rest] = [1, 2, 3, 4, 5]; // 剩余元素
// 交换变量
let a = 1, b = 2;
[a, b] = [b, a];
// 对象解构
const { name, age } = { name: 'John', age: 30 };
const { name: personName } = { name: 'John' }; // 重命名
const { name, country = 'USA' } = { name: 'John' }; // 默认值
扩展运算符
javascript
// 数组扩展
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
// 对象扩展
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }
// 函数参数
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
// 函数调用
const numbers = [1, 2, 3, 4, 5];
Math.max(...numbers); // 等价于 Math.max(1, 2, 3, 4, 5)
类 (ES6)
javascript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, I'm ${this.name}`;
}
static species() {
return 'Homo sapiens';
}
get birthYear() {
return new Date().getFullYear() - this.age;
}
set age(value) {
if (value < 0) throw new Error('Age cannot be negative');
this._age = value;
}
}
// 继承
class Student extends Person {
constructor(name, age, grade) {
super(name, age); // 调用父类构造函数
this.grade = grade;
}
study() {
return `${this.name} is studying in grade ${this.grade}`;
}
}
模块系统
ES6 模块
javascript
// 导出
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export default class Calculator { }
// 重命名导出
export { add as addNumbers };
// 导入
import Calculator from './calculator.js';
import { PI, add } from './math.js';
import { add as addNumbers } from './math.js';
import * as math from './math.js'; // 整体导入
import './side-effect.js'; // 只执行副作用
常用工具函数
类型检测
javascript
// 检测数据类型
function getType(value) {
return Object.prototype.toString.call(value).slice(8, -1);
}
// 深拷贝
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') return obj;
if (obj instanceof Date) return new Date(obj);
if (obj instanceof Array) return obj.map(item => deepClone(item));
if (typeof obj === 'object') {
const cloned = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
cloned[key] = deepClone(obj[key]);
}
}
return cloned;
}
}
// 防抖
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
// 节流
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
数组工具
javascript
// 数组去重
const unique = [...new Set([1, 2, 2, 3, 3, 4])]; // [1, 2, 3, 4]
// 数组分组
const grouped = array.reduce((acc, item) => {
const key = item.category;
acc[key] = acc[key] || [];
acc[key].push(item);
return acc;
}, {});
// 数组分块
function chunkArray(arr, chunkSize) {
const chunks = [];
for (let i = 0; i < arr.length; i += chunkSize) {
chunks.push(arr.slice(i, i + chunkSize));
}
return chunks;
}
字符串工具
javascript
// 驼峰转换
function toCamelCase(str) {
return str.replace(/[-_\s]+(.)?/g, (match, chr) => chr ? chr.toUpperCase() : '');
}
// 首字母大写
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
// 生成随机字符串
function randomString(length) {
return Math.random().toString(36).substring(2, length + 2);
}
浏览器API
localStorage/sessionStorage
javascript
// 存储数据
localStorage.setItem('key', 'value');
sessionStorage.setItem('key', 'value');
// 获取数据
const value = localStorage.getItem('key');
// 删除数据
localStorage.removeItem('key');
localStorage.clear(); // 清空所有
// JSON存储
localStorage.setItem('user', JSON.stringify({ name: 'John', age: 30 }));
const user = JSON.parse(localStorage.getItem('user'));
URL处理
javascript
// URLSearchParams
const params = new URLSearchParams(window.location.search);
const id = params.get('id');
// 创建URL参数
const urlParams = new URLSearchParams();
urlParams.append('name', 'John');
urlParams.append('age', '30');
const queryString = urlParams.toString(); // 'name=John&age=30'
定时器
javascript
// setTimeout
const timeoutId = setTimeout(() => {
console.log('延迟执行');
}, 1000);
// clearTimeout
clearTimeout(timeoutId);
// setInterval
const intervalId = setInterval(() => {
console.log('定期执行');
}, 1000);
// clearInterval
clearInterval(intervalId);
// requestAnimationFrame (用于动画)
function animate() {
// 动画逻辑
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
这份速查表涵盖了JavaScript开发中的核心概念和常用方法,可作为日常开发的快速参考。