概述

全称 ECMAScript 6.0 2015.06 发版;国际化组织ECMA 制定了浏览器脚本语言的标准,即ECMAScript;

以下只整理部分ES6扩展;

函数的扩展

  1. 参数默认值
1
function fn(x = 1, y = 2, z) {};
  1. 箭头函数
1
const fn = (a) => a;
  1. catch 参数省略
1
2
3
4
5
try {

} catch {
// catch(err){}
}
  1. 参数的尾逗号
1
function fn(a, b,) {}  //es2017之前报错

数组的扩展

  1. 扩展运算符
1
2
3
4
5
console.log(...[1, 2, 3]);
// 1 2 3

[...'script']
// ['s','c','r','i','p','t']
  1. Array.from()
  • 将类数组和部署了Iterator接口的对象转成真正的数组
1
2
3
4
5
6
7
8
let obj = { 0: 1, 1: 2, 2: 3, length: 3 };
Array.from(obj) // [1,2,3]

let set = new Set([12, 13]);
Array.from(set);//[12,13]

Array.from('hello');
// ['h','e','l','l','o']
  1. Array.of()
  • 将一数值转化为数组
1
2
3
4
Array.of() //[]
Array.of(1) //[1]
Array.of(13, 18) //[13,18]
Array.of(1).length // 1
  1. .find()和 .findIndex()
  • 找到第一个符合条件的成员
1
2
[3, 4, 6, 8].find(n => n < 5);// 3
[3, 4, 6, 8].findIndex(n => n < 5); // 0
  1. .fill
1
[1, 2, 3].fill('a') // ['a','a','a']
  1. .entries(),.keys() 和 .values()
  • 用来遍历数组
1
2
3
4
5
6
for (let index of [1, 2].keys()) {
console.log(index) // 0 1 ...
}
//or use next
[1, 2].values().next() // 1
[1, 2].values().next() // 2
  1. .includes()
  • 表示某个数组是否包含某项
1
2
[1, 2, 3].includes(1); // true
[1, 2, 3].includes(0); // false
  1. .flat(),.flatMap()
  • 拉平数组
1
2
3
4
5
[1, 2, [5, 5]].flat(1);  // 1 代表拉平层数
// [1,2,5,5]

[2, 3, 4].flatMap((x) => [x, x * 2])
// [2, 4, 3, 6, 4, 8]

对象的新增

  1. super关键字
  • 关键字super,指向当前对象的原型对象
1
2
3
4
5
6
7
8
9
10
11
const hello = {
value: 'hello'
}
const obj = {
value: 'world',
say() {
return super.value;
}
}
Object.setPrototypeOf(obj, hello);
obj.say(); // hello
  1. 解构赋值
1
2
3
4
5
6
7
const { x, y, ...z } = { x: 1, y: 2, z: 3, w: 4 };
x // 1
y // 2
z // {z:3:w:4}
const { z: t, w } = z;
t // 3
w // 4
  1. Object.is()
1
2
3
Object.is('t', 't'); //true
Object.is({}, {}); //false
Object.is(NaN, NaN) //true
  1. Object.assign()
1
2
3
let t = { x: 1, y: 2 };
let s = { z: 3 };
Object.assign(t, s, {});//{x:1,y:2,z:3}
  1. __proto__属性,Object.setPrototypeOf(),Object.getPrototypeOf()
  • Object.setPrototypeOf()
1
2
3
4
5
let t = { y: 1 }
let f = { x: 2 }
const o = Object.setPrototypeOf(f, t);
o.y // 1
o.x // 2
  • Object.getPrototypeOf()
1
2
3
4
5
6
7
8
9
10
11
12
function Rectangle() {
// ...
}

const rec = new Rectangle();

Object.getPrototypeOf(rec) === Rectangle.prototype
// true

Object.setPrototypeOf(rec, Object.prototype);
Object.getPrototypeOf(rec) === Rectangle.prototype
// false
  1. Object.keys(),Object.values(),Object.entries()
1
2
3
4
5
6
let 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]];

const _map=new Map(Object.entries(obj));
  1. Object.fromEntries()
  • Object.entries() 的逆操作
    1
    2
    Object.fromEntries([[name,'tom'],[age,18]]);
    // {name:tom,age:18}