ES2023(ES14)新特性有什么?

发布于:2024-08-08 ⋅ 阅读:(132) ⋅ 点赞:(0)

1. Array.prototype.with

with 方法返回一个新数组,替换指定索引处的元素

const arr = ['a', 'b', 'c', 'd'];
const res = arr.with(2, 'f');
console.log(res);//['a', 'b', 'f', 'd']
console.log(arr);//['a', 'b', 'c', 'd']
Array.prototype.toSorted  

2. Array.prototype.toSorted

toSorted 方法返回一个新的已排序数组,不改变原数组。

const numbers = [5, 3, 2, 4, 1];
const sortedNumbers = numbers.toSorted();
console.log(sortedNumbers); // [1, 2, 3, 4, 5]
console.log(numbers); // [5, 3, 2, 4, 1]  // 原数组不变

3. Array.prototype.toReversed

toReversed 方法返回一个新的数组,其元素顺序是原数组的反转。 和reverse()类似,但它会改变原数组

const numbers = [5, 3, 2, 4, 1];
const sortedNumbers = numbers.toSorted();
console.log(sortedNumbers); // [1, 2, 3, 4, 5]
console.log(numbers); // [5, 3, 2, 4, 1]  // 原数组不变
Array.prototype.toSpliced  
const months = ['Jan', 'Mar', 'Apr', 'May'];

// 在索引 1 处添加一个元素
const months2 = months.toSpliced(1, 0, 'Feb');
console.log(months2); // ["Jan", "Feb", "Mar", "Apr", "May"]


// 从第 2 个索引开始删除两个元素
const months3 = months.toSpliced(2);
console.log(months3); // ["Jan", "Mar"]

console.log(months); //['Jan', 'Mar', 'Apr', 'May'];

4. Array.prototype.toSpliced

toSpliced 是一种数组操作方法,它与 splice 类似,但toSpliced不会修改原数组,而是返回一个新数组,包含删除和新增元素后的结果。它在操作数组时更加安全,因为不会改变原始数据。

const months = ['Jan', 'Mar', 'Apr', 'May'];

// 在索引 1 处添加一个元素
const months2 = months.toSpliced(1, 0, 'Feb');
console.log(months2); // ["Jan", "Feb", "Mar", "Apr", "May"]

// 从第 2 个索引开始删除两个元素
const months3 = months.toSpliced(2);
console.log(months3); // ["Jan", "Mar"]

console.log(months); //['Jan', 'Mar', 'Apr', 'May'];

5. Object.hasOwn

Object.hasOwnObject.prototype.hasOwnProperty 的简写,检查属性是否是对象的自身属性,并不是继承来的。

const obj = {
  a: 1,
};
console.log(obj);
console.log(Object.hasOwn(obj, 'a'));//true
console.log(Object.hasOwn(obj, 'valeOf'));//false

6. findLast() 和 findLastIndex()

findLast(): 由后往前通过索引查找数组中符合条件的第一个元素。

const array1 = [5, 12, 50, 130, 44];

const found = array1.findLast((element) => element > 45);

console.log(found);// 130

findLastIndex(): 由后往前通过索引查找数组中符合条件的第一个元素所在的索引。

const array1 = [5, 12, 50, 130, 44];

const isLargeNumber = (element) => element > 45;

console.log(array1.findLastIndex(isLargeNumber));//3

7. Hashbang 语法

Hashbang 注释是一种特殊的注释语法,它会以#!开头,后面仅跟着解释器(interpreter) 的路径,并且只会在脚本或是模组的最开始有效。
以下方代码为例,这段代码是告诉系统,用 Node.js 来执行文件:

#!/usr/bin/env node
console.log('Hello, world!');

8. WeakMap 支持 Symbol 作为 key

Symbols 具有唯一的标识,适合生成唯一的键。
🔍什么是Symbol?在实际开发中怎么用?

const keyA = Symbol('fruit');
const keyB = Symbol('fruit');

const map = new WeakMap();
map.set(keyA, 'apple');

console.log(map.get(keyA)); // "apple"
console.log(map.get(keyB)); // undefined

网站公告

今日签到

点亮在社区的每一天
去签到