当前位置: 首页 > ds >正文

ES6 核心语法手册

ES6 核心语法手册


一、变量声明

关键字作用域是否可重定义是否可修改特性
let块级作用域替代 var 的首选
const块级作用域声明常量(对象属性可修改)
// 示例
let name = "Alice";
name = "Bob"; // ✅const PI = 3.14;
// PI = 3.15; ❌ 报错const user = { name: "John" };
user.name = "Mike"; // ✅ 对象属性可修改

二、箭头函数

// 传统函数
function sum(a, b) {return a + b;
}// 箭头函数
const sum = (a, b) => a + b;// 特性:
// 1. 无自己的 this(继承外层上下文)
// 2. 不能用作构造函数
// 3. 无 arguments 对象// 示例:this 绑定
const obj = {value: 10,getValue: function() {setTimeout(() => {console.log(this.value); // ✅ 输出 10(箭头函数继承 this)}, 100);}
};

三、模板字符串

const name = "Alice";
const age = 28;// 多行字符串
const bio = `姓名:${name}
年龄:${age}
职业:工程师`;// 表达式计算
console.log(`明年年龄:${age + 1}`); // 输出:明年年龄:29// 标签模板(高级用法)
function highlight(strings, ...values) {return strings.reduce((result, str, i) => `${result}${str}<mark>${values[i] || ''}</mark>`, '');
}
highlight`Hello ${name}`; // <mark>Hello</mark><mark>Alice</mark>

四、解构赋值

// 数组解构
const [first, second, , fourth] = [10, 20, 30, 40];
console.log(first); // 10// 对象解构
const { name, age: userAge } = { name: "Bob", age: 30 };
console.log(userAge); // 30// 函数参数解构
function getUser({ id, name = "Unknown" }) {console.log(`ID: ${id}, Name: ${name}`);
}
getUser({ id: 1 }); // ID: 1, Name: Unknown

五、扩展运算符与剩余参数

// 数组扩展
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]// 对象扩展
const obj1 = { a: 1 };
const obj2 = { ...obj1, b: 2 }; // { a: 1, b: 2 }// 剩余参数
function sum(...numbers) {return numbers.reduce((acc, cur) => acc + cur, 0);
}
sum(1, 2, 3); // 6

六、类与继承

class Animal {constructor(name) {this.name = name;}speak() {console.log(`${this.name} makes a noise`);}
}class Dog extends Animal {constructor(name, breed) {super(name);this.breed = breed;}speak() {super.speak();console.log("Woof!");}
}const rex = new Dog("Rex", "Labrador");
rex.speak();

七、模块化

// 📁 math.js
export const PI = 3.14159;
export function square(x) { return x * x; }
export default function cube(x) { return x * x * x; }// 📁 app.js
import { PI, square } from './math.js';
import cube from './math.js'; // 导入默认导出console.log(square(PI)); // 9.8690227281

八、Promise 与异步

// 创建 Promise
const fetchData = () => new Promise((resolve, reject) => {setTimeout(() => Math.random() > 0.5 ? resolve("成功!") : reject("失败!"), 1000);
});// 使用 Promise
fetchData().then(data => console.log(data)).catch(error => console.error(error));// Async/Await
async function getData() {try {const result = await fetchData();console.log(result);} catch (error) {console.error(error);}
}

九、新增数据结构

类型特性常用方法
Set值唯一的集合add(), delete(), has()
Map键值对集合(键可以是任意类型)set(), get(), has()
WeakSet弱引用集合(仅存储对象)add(), delete(), has()
WeakMap弱引用键值对(键必须是对象)set(), get(), has()
// Set 示例
const uniqueNumbers = new Set([1, 2, 2, 3]);
console.log([...uniqueNumbers]); // [1, 2, 3]// Map 示例
const userMap = new Map();
userMap.set(1, { name: "Alice" });
console.log(userMap.get(1)); // { name: "Alice" }

十、其他重要特性

  1. Symbol - 创建唯一标识符

    const id = Symbol("uniqueID");
    console.log(id === Symbol("uniqueID")); // false
    
  2. 迭代器与生成器

    function* idGenerator() {let id = 1;while (true) yield id++;
    }
    const gen = idGenerator();
    console.log(gen.next().value); // 1
    
  3. Proxy 与 Reflect(元编程)

    const handler = {get(target, prop) {return prop in target ? target[prop] : 37;}
    };
    const p = new Proxy({}, handler);
    console.log(p.a); // 37
    

ES6 兼容性解决方案

  1. 使用 Babel 进行代码转换
  2. 配合 Webpack/Rollup 打包
  3. 核心特性现代浏览器已原生支持(可查 Can I Use)
http://www.xdnf.cn/news/12999.html

相关文章:

  • C语言 学习 数组(一维数组,多维数组,字符数组,字符串) 2025年6月8日09:21:39
  • Σ∆ 数字滤波
  • Linux 用户层 和 内核层锁的实现
  • 嵌入式面试提纲
  • debian12拒绝海外ip连接
  • PyCharm和VS Code哪个更适合初学者
  • idea 启动jar程序并调试
  • 机器学习模型选择指南:从问题到解决方案
  • 华为开源自研AI框架昇思MindSpore应用案例:ICT实现图像修复
  • 前端现行架构浅析
  • 主流嵌入式Shell工具性能对比
  • Python计算字符串距离算法库textdistance详解与应用实战
  • Python_day48随机函数与广播机制
  • Framework开发之IMS逻辑浅析1--关键线程及作用
  • Spring AOP代理对象生成原理
  • 在Unity中Update和Fixedupdate有什么区别
  • 【读论文】OpenAI o3与o4系统模型技术报告解读
  • 数据源指的是哪里的数据,磁盘中还是内存中
  • 调试快捷键 pycharm vscode
  • 掌握Git核心:版本控制、分支管理与远程操作
  • 联邦学习与边缘计算结合
  • 一种停车场自动停车导航器的设计(论文+源码)
  • grpc和http的区别
  • 自动驾驶科普(百度Apollo)学习笔记
  • 【AI智能体】Dify 从部署到使用操作详解
  • 解决limit 1000000加载慢的问题
  • 【每天学点 Go 知识】Go 基础知识 + 基本数据类型快速入门
  • 【大模型RAG】Docker 一键部署 Milvus 完整攻略
  • 基于规则的自然语言处理
  • 基于多维视角的大模型提升认知医疗过程层次激励编程分析