Contents

ES2022 都有哪些新特性

ES2022 有哪些新特性!

1. Object.hasOwn()

在ES2022之前,可以使用Object.prototype.hasOwnProperty() 来检查一个属性是否属于对象。

Object.hasOwn特性是一种更简洁、更可靠的检查属性是否直接设置在对象上的方法:

const example = {
  property: '123'
}

console.log(Object.prototype.hasOwnProperty.call(example,'property'));
console.log(Object.hasOwn(example,'property'))

// output: true true

该特性的浏览器支持如下所示:

https://cdn.jsdelivr.net/gh/BallerJay/oss_images@master/blog/2022/07/2022-07-02/image-20220702220352432.png

2. at()

at() 是一个数组方法,用于通过给定索引来获取数组元素。当给定索引为正时,这种新方法与使用括号表示法访问具有相同的行为。当给出负整数索引时,就会从数组的最后一项开始检索:

const arr = [0,1,2,3,4];

console.log(arr[arr.length - 1]); // 4
console.log(arr.at(-1)); // 4

除了数组,字符串也可以使用at()方法进行索引:

const str = "hello world";

console.log(str[str.length - 1]); // d
console.log(str.at(-1)); // d