ES6 ES14

96 阅读2分钟

Array.prototype.with

  • 基于索引修改单个元素,返回新的数组
const arr4 = ["I", "am", "the", "Walrus"];

// 用 "Ape Man" 替换字符串 "Walrus"。
const newArr4 = arr4.with(3, "Ape Man");

console.log(newArr4);

Array.prototype.toSorted

  • 创建新的数组
let arr = [5, 4, 2, 3, 1];
arr === arr.sort(); // true - [1, 2, 3, 4, 5]

arr === arr.toSorted(); // false - [1, 2, 3, 4, 5]
  • 接收一个可选参数作为比较函数

  • 创建一个按降序排列的新数组

const numbers = [10, 5, 2, 7, 3, 9, 1, 6, 4];
const sortedNumbers = numbers.toSorted((a, b) => {
  return b - a;
});
console.log(sortedNumbers); // [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
  • 可以应用于对象数组,需要提供一个使用对象上的数据的比较函数(因为对象没有自然的排序方式)
// 比较对象
const objects = [
  { name: "John", age: 30 },
  { name: "Jane", age: 25 },
  { name: "Bill", age: 40 },
  { name: "Mary", age: 20 }
];
const sortedObjects = objects.toSorted((a, b) => {
  return a.name.localeCompare(b.name);
});
console.log(sortedObjects);
// [{"name":"Bill","age":40},{"name":"Jane","age":25},{"name":"John","age":30},{"name":"Mary","age":20}]

Array.prototype.with

新的 with() 方法允许您基于索引修改单个元素,并返回一个新的数组。因此,如果您知道索引和新值,这个方法非常方便。

const arr4 = ["I", "am", "the", "Walrus"];

// 用 "Ape Man" 替换字符串 "Walrus"。
const newArr4 = arr4.with(3, "Ape Man");

console.log(newArr4);

Array.prototype.toSpliced

  • 只存在于 Array 中

  • 创建新的数组

const arr = ["red", "orange", "yellow", "green", "blue", "purple"];
const newArr = arr.toSpliced(2, 1, "pink", "cyan");
console.log(newArr);
// ["red", "orange", "pink", "cyan", "green", "blue", "purple"]
console.log(newArr[3]);
// 'cyan'
console.log(arr[3]);
// 'green'

Symbol 作为 WeakMap 的键

  • 在这之前,WeakMap仅允许对象作为键值,新特性更容易创建和共享key
var map = new WeakMap(); // 创建一个弱映射
function useSymbol(symbol){
    doSomethingWith(symbol);
    var called = map.get(symbol) || 0
  • 允许从外部调用者调用计数器,不再有引用时释放映射条目

  • 代码不知道何时不再需要引用,如果使用普通的 Map,将会导致内存泄漏

  • 使用 WeakMap,可以确保垃圾回收在不再存在对键符号的引用时删除映射条目

Array.prototype.toReversed

Array.prototype.findLast

Array.prototype.findLastIndex

ES14新特性揭秘,对前端开发有哪些影响? - 掘金 (juejin.cn)

TBC

  • TypedArray