ES6 特性
let 和 const
箭头函数
模板字符串
解构赋值
const obj = { a: 1, b: 2 };
const { a, b } = obj;
console.log(a, b); // 1, 2
const arr = [1, 2, 3];
const [x, y, z] = arr;
console.log(x, y, z); // 1, 2, 3
默认参数
function foo(a, b = 2, c = 3) {}
剩余(rest)参数
function sum(...nums) {
return nums.reduce((a, b) => a + b);
}
sum(1, 2, 3, 4, 5);
扩展运算符
const arr1 = [1, 2, 3];
const arr2 = [...arr, 4, 5];
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj, c: 3 };
扩展对象字面量
对象属性简写
const name = "zhangsan";
const age = 18;
const preson = { name, age };
对象方法简写
const person = {
name: "zhangsan",
greet() {
console.log("Hello!");
},
};
for…of 循环
模块化(import/export)
// foo.js
export const foo = () => {};
// main.js
import { foo } from "./foo";
默认导出
// foo.js
export default () => {};
// main.js
import foo from "./foo";
foo();
类(class)
class Person {
constructor(name) {
this.name = name;
}
say() {}
}
class Student extends Person {
say() {
console.log(`I'm a student, ${this.name}`);
}
}
const s = new Student("zhangsan");
s.say();
Promise
Symbol
生成器和迭代器
Set 和 Map
静态方法
class MathUtil {
static add(a, b) {
return a + b;
}
}
console.log(MathUtil.add(1, 2));
字符串新方法
- startsWith
- endsWith
- includes
数组新方法
- find
- findIndex
对象合并
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 5 };
const obj3 = { ...obj1, ...obj2 };
空值合并运算符
const foo = null ?? "default";
const bar = 0 ?? 42;
console.log(bar); // 0
块级作用域
Proxy
Proxy 对象用于创建一个对象的代理,从而实现基本操作的拦截和自定义(如属性查找、赋值、枚举、函数调用等)。
const target = {
message: "hello world",
};
const handler = {
get: (obj, prop) => {
return prop in obj ? obj[prop] : "not fount prop";
},
set: (obj, prop, value) => {
return value;
},
};
const proxy = new Proxy(target, handler);