ES11,ES12,ES13(超详细!!!,附用法代码)

目录

ES11(2020)

Optional Chaining(可选链操作符)

Nullish Coalescing Operator (空值合并操作符)

BigInt

Promise.allSettled()

import()

globalThis

ES12(2021)

String.prototype.replaceAll()

 Promise.any()

逻辑运算符和赋值表达式

数字分隔符

下划线 (_) 分隔符

Intl.ListFormat

Intl.DateTimeFormat API 中的 dateStyle 和 timeStyle 的配置项

ES13(2022)

声明类的字段

私有类字段和成员:

静态类字段和静态私有方法 

类静态块:

检查对象中的私有字段

Strings、Arrays、TypedArrays的新增at方法:

Object.hasOwn(object, property) 


ES11(2020)

Optional Chaining(可选链操作符)

Optional Chaining允许在访问对象的属性或方法时,如果中间的属性或方法不存在,不会导致错误,而是返回undefined。

?.用户检测不确定的中间节点

const user = {
  name: 'John',
  address: {
    city: 'New York'
  }
};

console.log(user.address?.city); // 'New York'
console.log(user.address?.country); // undefined

Nullish Coalescing Operator (空值合并操作符)

Nullish Coalescing Operator用于判断一个变量是否为null或undefined,如果是则返回默认值。

表达式在 ?? 的左侧 运算符求值为undefined或null,返回其右侧。

let user = {
    u1: 0,
    u2: false,
    u3: null,
    u4: undefined
    u5: '',
}
let u2 = user.u2 ?? '用户2'  // false
let u3 = user.u3 ?? '用户3'  // 用户3
let u4 = user.u4 ?? '用户4'  // 用户4
let u5 = user.u5 ?? '用户5'  // ''

BigInt

ES11引入了BigInt数据类型,用于表示大整数,可以存储任意精度的整数。

新基本数据类型BigInt——任意精度的整数

const bigIntValue = 9007199254740991n + 1n;
console.log(bigIntValue); // 9007199254740992n

Promise.allSettled()

Promise.allSettled()方法接收一组Promise对象,返回一个Promise对象,当所有Promise都已经settled(即已经完成或已经拒绝)时,返回一个包含每个Promise结果的对象。

返回一个在所有给定的promise已被决议或被拒绝后决议的promise,并带有一个对象数组,每个对象表示对应的promise结果

const promises = [
  Promise.resolve('Resolved'),
  Promise.reject('Rejected'),
  Promise.resolve('Resolved Again')
];

Promise.allSettled(promises)
  .then(results => console.log(results));

import()

按需导入

globalThis

通过 globalThis,可以使用一种标准的方法拿到全局对象,而不用关心代码的运行环境。

  • 浏览器:window
  • worker:self
  • node:global
var getGlobal = function () {
    // the only reliable means to get the global object is
    // `Function('return this')()`
    // However, this causes CSP violations in Chrome apps.
    if (typeof self !== 'undefined') { return self; }
    if (typeof window !== 'undefined') { return window; }
    if (typeof global !== 'undefined') { return global; }
    throw new Error('unable to locate global object');
};

var globals = getGlobal();

if (!globals.Reflect) {
    defineProperty(globals, 'Reflect', {}, true);
}

ES12(2021)

String.prototype.replaceAll()

String.prototype.replaceAll()方法用于替换字符串中所有匹配的子字符串。

返回一个全新的字符串,所有符合匹配规则的字符都将被替换掉

const str = 'hello world hello world';
const newStr = str.replaceAll('hello', 'hi');
console.log(newStr); // 'hi world hi world'

 Promise.any()

Promise.any()方法接收一组Promise对象,只要其中有一个Promise变为fulfilled状态,就会返回该Promise的值

const promises = [
  Promise.reject('Rejected 1'),
  Promise.resolve('Resolved 2'),
  Promise.reject('Rejected 3')
];

Promise.any(promises)
  .then(result => console.log(result)); // 'Resolved 2'

逻辑运算符和赋值表达式

ES12引入了逻辑赋值运算符,包括&&=、||=和??=。这些运算符结合了逻辑运算符和赋值操作符。

let x = 1;
x &&= 2; // 相当于 x = x && 2;
console.log(x); // 2

let y = null;
y ||= 3; // 相当于 y = y || 3;
console.log(y); // 3

let z = 0;
z ??= 4; // 相当于 z = z ?? 4;
console.log(z); // 0

数字分隔符

ES12允许在数字字面量中使用下划线作为分隔符,以提高数字的可读性.

const bigNumber = 1_000_000_000;
console.log(bigNumber); // 1000000000

下划线 (_) 分隔符

数字太长会导致可读性很差。使用了数字分隔符 _ (下划线),就可以让数字读的更清晰:

Intl.ListFormat

Intl.ListFormat 是一个构造函数,用来处理和多语言相关的对象格式化操作。

const list = ['Apple', 'Orange', 'Banana']
new Intl.ListFormat('en-GB', { style: 'long', type: 'conjunction' }).format(list);
// "Apple, Orange and Banana"
new Intl.ListFormat('zh-cn', { style: 'short', type: 'conjunction' }).format(list);
// 会根据语言来返回相应的格式化操作
// "Apple、Orange和Banana"

Intl.DateTimeFormat API 中的 dateStyle 和 timeStyle 的配置项

let o = new Intl.DateTimeFormat("en" , {
  timeStyle: "short"
});
console.log(o.format(Date.now())); // "13:31"
let o = new Intl.DateTimeFormat("en" , {
  dateStyle: "short"
});
console.log(o.format(Date.now())); // "21.03.2012"
// 可以通过同时传入 timeStyle 和 dateStyle 这两个参数来获取更完整的格式化时间的字符串
let o = new Intl.DateTimeFormat("en" , {
  timeStyle: "medium",
  dateStyle: "short"
});
console.log(o.format(Date.now())); // "21.03.2012, 13:31"

ES13(2022)

声明类的字段

类的字段定义和初始化是在类的构造函数中完成的。但是在ES13的提案中,类字段可以在类的顶层被定义和初始化

class Point {
   name;
   title;
   size = 1;
}

私有类字段和成员

在ES13之前,类字段只能在构造函数中声明,并且成员通常使用下划线(_)前缀来表示私有性,但这仅仅是一个约定,实际上这些成员仍然可以从类外部访问和修改。在ES13中,通过在类字段前添加(#)可以明确地定义私有字段和成员。

class MyClass {  
    #privateField = 'private';  
    publicField = 'public';  
  
    getPrivateField() {  
        return this.#privateField;  
    }  
}  
  
const instance = new MyClass();  
console.log(instance.publicField); // 输出 'public'  
console.log(instance.#privateField); // 报错,因为 #privateField 是私有的  
console.log(instance.getPrivateField()); // 输出 'private',通过 getter 可以访问私有字段

静态类字段和静态私有方法 

在之前的类的字段私有方法提案的基础上,为JavaScript类增加了静态公共字段静态私有方法静态私有字段的特性。

class MyStaticClass {  
    static #staticPrivateField = 'static private';  
    static staticPublicField = 'static public';  
  
    static #staticPrivateMethod() {  
        return 'This is a static private method';  
    }  
  
    static getStaticPrivateField() {  
        return this.#staticPrivateField;  
    }  
}  
  
console.log(MyStaticClass.staticPublicField); // 输出 'static public'  
console.log(MyStaticClass.#staticPrivateField); // 报错,因为 #staticPrivateField 是私有的  
console.log(MyStaticClass.getStaticPrivateField()); // 输出 'static private',通过 getter 可以访问静态私有字段

类静态块

ES13引入了类静态块,它允许开发者定义仅在创建类时执行一次的静态代码块。这与C#和Java中的静态构造函数相似。

class MyClass {  
    static {  
        console.log('This block will execute only once when the class is created.');  
    }  
}  
  
new MyClass(); // 输出 'This block will execute only once when the class is created.'  
new MyClass(); // 不会有任何输出,因为静态块只执行一次

检查对象中的私有字段

开发者现在可以使用in运算符来方便地检查对象是否包含某个特定的私有字段。

class MyClass {  
    #privateField = 'private';  
}  
  
const instance = new MyClass();  
console.log('privateField' in instance); // 输出 false,因为 #privateField 是私有的  
console.log('#privateField' in instance); // 输出 true,使用 # 符号可以检查私有字段

Strings、Arrays、TypedArrays的新增at方法

 新增一个新的数组方法,通过给定的索引来获取一个元素。当给定的索引为正数时,这个新方法的行为与使用括号符号的访问相同,但是当我们给定一个负整数的索引时,它就像python的 "负数索引 "一样工作,这意味着at()方法以负整数为索引,从数组的最后一项往后数。所以该方法可以被执行为array.at(-1),它的行为与array[array.length-1]相

const list = [1,2,3,4,5,6];
console.log(list.at(-1)); // 6
console.log(list.at(-2)); // 5

Object.hasOwn(object, property) 

简单讲就是使用 Object.hasOwn 替代 Object.prototype.hasOwnProperty.call

const person = {name: 'lxm'}
console.log(Object.prototype.hasOwnProperty.call(person, 'name')) // true

console.log(Object.hasOwn(person, 'name')) // tr

  • 30
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值