关于前端:ES6-常用扩展

3次阅读

共计 2089 个字符,预计需要花费 6 分钟才能阅读完成。

概述

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

以下只整顿一部分;

函数的扩大

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

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

数组的扩大

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

[...'script']
// ['s','c','r','i','p','t']
  1. Array.from()
  • 将类数组和部署了 Iterator 接口的对象转成真正的数组
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()
  • 将一数值转化为数组
Array.of() //[]
Array.of(1) //[1]
Array.of(13, 18) //[13,18]
Array.of(1).length // 1
  1. .find().findIndex()
  • 找到第一个符合条件的成员
[3, 4, 6, 8].find(n => n < 5);// 3
[3, 4, 6, 8].findIndex(n => n < 5); // 0
  1. .fill
[1, 2, 3].fill('a') // ['a','a','a']
  1. .entries().keys().values()
  • 用来遍历数组
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, 3].includes(1); // true
[1, 2, 3].includes(0); // false
  1. .flat().flatMap()
  • 拉平数组
[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,指向以后对象的原型对象
const hello = {value: 'hello'}
const obj = {
    value: 'world',
    say() {return super.value;}
}
Object.setPrototypeOf(obj, hello);
obj.say(); // hello 
  1. 解构赋值
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()
Object.is('t', 't'); //true
Object.is({}, {}); //false
Object.is(NaN, NaN) //true
  1. Object.assign()
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()
let t = {y: 1}
let f = {x: 2}
const o = Object.setPrototypeOf(f, t);
o.y // 1
o.x // 2
  • Object.getPrototypeOf()
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()
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() 的逆操作】
Object.fromEntries([[name,'tom'],[age,18]]);
// {name:tom,age:18}
正文完
 0