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

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)

相关文章:

  • SQL导出Excel支持正则脱敏
  • AD规则设置-铜皮规则,阻焊规则,实时DRC
  • AI时代:学习永不嫌晚,语言多元共存
  • LambdaqueryWrapper的介绍与使用
  • 第十二讲 | 二叉搜索树
  • JavaScript 语法结构
  • Android 大文件分块上传实战:突破表单数据限制的完整方案
  • 用 AI 开发 AI:原汤化原食的 MCP 桌面客户端
  • 【评测】Qwen3-Embedding模型初体验
  • MSYS2 环境配置与 Python 项目依赖管理笔记
  • android计算器代码
  • typeof运算符 +unll和undefined的区别
  • 树状数组学习笔记
  • 人工智能学习07-函数
  • MATLAB遍历生成20到1000个节点的无线通信网络拓扑推理数据
  • 动态模块加载的响应式架构:从零到一的企业级实战指南
  • 量化面试绿皮书:7. 100的阶乘中有多少个尾随零
  • 《PyTorch深度学习入门》
  • 05.查询表
  • 探索双曲函数:从定义到MATLAB可视化
  • 普通网站制作/免费建网站的平台
  • 网站换程序301/企业营销策划案例
  • 了解网站基本知识/百度提交收录入口
  • 做网站优化的好处/淘宝关键词指数
  • 82端口做网站/个人网上卖货的平台
  • 企业网站设计注意事项/适合企业员工培训的课程