Modern JavaScript Cheatsheet 现代JavaScript速查手册

Modern JavaScript Cheatsheet 现代JavaScript速查手册

modern-js-cheatsheet Cheatsheet for the JavaScript knowledge you will frequently encounter in modern projects. modern-js-cheatsheet 项目地址: https://gitcode.com/gh_mirrors/mo/modern-js-cheatsheet

前言

动机

本手册旨在为现代JavaScript项目中频繁出现的核心概念提供快速参考指南。它并非JavaScript基础教程,而是面向已有基础但需要快速查阅ES6+新特性的开发者,特别是那些在学习React等现代框架时遇到JavaScript语法困惑的人群。

手册中我会适当加入一些个人观点,但会明确标注这些属于主观建议。

提示: 本手册大部分内容基于ES2015(俗称ES6)更新,你可以通过专业网站查看完整的ES6新特性列表。

核心概念

变量声明:var、const、let

快速对比

JavaScript提供三种变量声明方式,各具特点:

| 类型 | 作用域 | 可重新赋值 | 可变更值 | 暂时性死区 | |------|--------|------------|----------|------------| | const | 块级 | × | √ | √ | | let | 块级 | √ | √ | √ | | var | 函数级 | √ | √ | × |

最佳实践建议:

  • 默认使用const
  • 需要重新赋值时使用let
  • 避免使用var
代码示例
const PI = 3.14;
PI = 3.1415 // 报错:常量不可重新赋值

let count = 1;
count = 2; // 允许重新赋值
深度解析
  1. var的缺陷
    • 函数作用域导致变量提升(hoisting)问题
    • 允许重复声明
    • 没有块级作用域
function varTest() {
  var x = 1;
  if (true) {
    var x = 2;  // 实际上是同一个变量
    console.log(x);  // 2
  }
  console.log(x);  // 2
}
  1. let/const的优势
    • 块级作用域
    • 存在暂时性死区(TDZ)
    • 禁止重复声明
function letTest() {
  let x = 1;
  if (true) {
    let x = 2;  // 不同的变量
    console.log(x);  // 2
  }
  console.log(x);  // 1
}
  1. const的特殊性
    • 必须初始化
    • 不能重新赋值
    • 但对于对象/数组,内容可以修改
const arr = [1, 2];
arr.push(3); // 允许
arr = [4, 5]; // 报错

箭头函数

核心优势
  1. 简洁语法
  2. 自动绑定外层this
  3. 隐式返回
典型用法
// 传统函数
function sum(a, b) {
  return a + b;
}

// 箭头函数
const sum = (a, b) => a + b;

// 单个参数可省略括号
const square = x => x * x;

// 无参数需要空括号
const greet = () => console.log("Hello");

// 多行语句需要大括号
const logObject = obj => {
  console.log("Object keys:");
  Object.keys(obj).forEach(key => {
    console.log(key);
  });
};
this绑定机制

传统函数的this取决于调用方式,箭头函数则继承外层this:

function Timer() {
  this.seconds = 0;
  
  // 传统函数需要额外绑定
  setInterval(function() {
    this.seconds++; // 错误!this指向window
  }, 1000);
  
  // 箭头函数自动绑定
  setInterval(() => {
    this.seconds++; // 正确
  }, 1000);
}

解构赋值

对象解构
const user = {
  id: 42,
  displayName: 'jdoe',
  fullName: {
    firstName: 'John',
    lastName: 'Doe'
  }
};

// 基本解构
const { id, displayName } = user;

// 重命名变量
const { displayName: userName } = user;

// 嵌套解构
const { fullName: { firstName } } = user;

// 默认值
const { role = 'user' } = user;
数组解构
const rgb = [255, 128, 0];

// 基本解构
const [red, green, blue] = rgb;

// 跳过元素
const [r, , b] = rgb;

// 剩余元素
const [firstColor, ...otherColors] = rgb;

// 默认值
const [x = 1, y = 2] = [10];

数组高阶方法

map - 数据转换
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);
// [2, 4, 6]
filter - 数据筛选
const evens = numbers.filter(n => n % 2 === 0);
// [2]
reduce - 数据聚合
const sum = numbers.reduce((total, n) => total + n, 0);
// 6
find - 元素查找
const users = [
  {id: 1, name: 'John'},
  {id: 2, name: 'Jane'}
];
const user = users.find(u => u.id === 2);
// {id: 2, name: 'Jane'}

扩展运算符(...)

数组展开
const parts = ['shoulders', 'knees'];
const body = ['head', ...parts, 'toes'];
// ['head', 'shoulders', 'knees', 'toes']
函数参数收集
function sum(...numbers) {
  return numbers.reduce((a, b) => a + b);
}
sum(1, 2, 3); // 6
对象展开
const obj1 = { foo: 'bar', x: 42 };
const obj2 = { ...obj1, y: 13 };
// { foo: 'bar', x: 42, y: 13 }

Promise异步处理

基本用法
const fetchData = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Data received');
      // 或 reject(new Error('Failed'));
    }, 1000);
  });
};

fetchData()
  .then(data => console.log(data))
  .catch(err => console.error(err));
async/await语法糖
async function processData() {
  try {
    const data = await fetchData();
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

类与继承

类定义
class Person {
  constructor(name) {
    this.name = name;
  }
  
  greet() {
    console.log(`Hello, ${this.name}!`);
  }
  
  static createAnonymous() {
    return new Person('Anonymous');
  }
}
继承
class Student extends Person {
  constructor(name, grade) {
    super(name);
    this.grade = grade;
  }
  
  study() {
    console.log(`${this.name} is studying`);
  }
}

总结

本手册涵盖了现代JavaScript开发中最常用的ES6+特性,包括:

  • 更安全的变量声明方式(let/const)
  • 简洁的箭头函数
  • 强大的解构赋值
  • 函数式数组操作
  • 扩展运算符的多种应用
  • Promise异步处理
  • 类与继承语法

掌握这些核心概念将大幅提升你的JavaScript开发效率和代码质量。建议在实际项目中多加练习,逐步将这些特性融入你的编码实践中。

modern-js-cheatsheet Cheatsheet for the JavaScript knowledge you will frequently encounter in modern projects. modern-js-cheatsheet 项目地址: https://gitcode.com/gh_mirrors/mo/modern-js-cheatsheet

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张姿桃Erwin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值