aurora-article icon indicating copy to clipboard operation
aurora-article copied to clipboard

js 数组的新方法

Open starryiu opened this issue 2 years ago • 0 comments

最近发现了数组的新方法,分别是toReversed()、toSorted()、toSpliced(),和原版的函数相比,它们不会改变原数组。

toReversed()

和 reverse() 相比,不会更改原数组,而是返回一个反转后的新数组。

const items = [1, 2, 3];
console.log(items); // [1, 2, 3]

const reversedItems = items.toReversed();
console.log(reversedItems); // [3, 2, 1]
console.log(items); // [1, 2, 3]

toSorted()

和 sort() 相比,不会更改原数组,而是返回一个排序后的新数组。

const values = [1, 10, 21, 2];
const sortedValues = values.toSorted((a, b) => a - b));
console.log(sortedValues); // [1, 2, 10, 21]
console.log(values); // [1, 10, 21, 2]

toSpliced()

和 splice() 相比,不会更改原数组,而是返回一个删除、添加和替换元素后的新数组。

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 = months2.toSpliced(2, 2);
console.log(months3); // ["Jan", "Feb", "May"]

// 在索引 1 处用两个新元素替换一个元素
const months4 = months3.toSpliced(1, 1, "Feb", "Mar");
console.log(months4); // ["Jan", "Feb", "Mar", "May"]

// 原数组不会被修改
console.log(months); // ["Jan", "Mar", "Apr", "May"]

新的分组方法 group()

和 lodash 的 groupBy 一样的,目前还在实验阶段,不要使用。

const inventory = [
  { name: "asparagus", type: "vegetables", quantity: 5 },
  { name: "bananas", type: "fruit", quantity: 0 },
  { name: "goat", type: "meat", quantity: 23 },
  { name: "cherries", type: "fruit", quantity: 5 },
  { name: "fish", type: "meat", quantity: 22 },
];
const result = inventory.group(({ type }) => type);

/* 结果是:
{
  vegetables: [
    { name: 'asparagus', type: 'vegetables', quantity: 5 },
  ],
  fruit: [
    { name: "bananas", type: "fruit", quantity: 0 },
    { name: "cherries", type: "fruit", quantity: 5 }
  ],
  meat: [
    { name: "goat", type: "meat", quantity: 23 },
    { name: "fish", type: "meat", quantity: 22 }
  ]
}
*/

总结

目前原生的兼容性很差,谷歌和微软浏览器可以,火狐则是直接报错,尽量在一些项目脚手架中去使用,这样会自动处理。

一些常见的会更改原始数据的方法,在使用时要注意一下。

/**
 * 数组
 * push pop shift unshift splice sort reverse
 * 对象
 * Object.assign 的第一个参数会被更改,不更改需要下面这种写法
 * Object.assign({},obj,newData) 或 {...obj,newData}
 * Reflect.deleteProperty
 */

starryiu avatar Jul 02 '23 00:07 starryiu