Array.from和set方法

119 阅读1分钟

ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。Set 本身是一个构造函数,用来生成 Set 数据结构。

数组去重

image.png

Array.from 方法可以将 Set 结构转为数组。我们可以专门编写使用一个去重的函数

image.png

字符去重

另外 Set 是如此强大,因此使用 Set 可以很容易地实现并集(Union)、交集(Intersect)和差集(Difference)。

image.png

let a = [1,2,3]; let b = [4,3,2]; //并集 let union = Array.from(new Set([…a,…b]))

//交集 let inter = […a].filter(x=new Set(b).has(x))

//补集

顺便学习Array.from的功能 1.把类数组或者集合转为数组,返回一个新数组 Array.from(arguments) Array.from(new Set([1,3,5]))

2.第二个参数是一个方法,返回一个新数组 Array.from([1,2,3,4],(item)=>item+1)

3.Array.from({length:10}) 创建length10的数组 Array.from(object,mapFunction,thisValue) object 必需,要转换为数组的对象。 mapFunction 可选,数组中每个元素要调用的函数。 thisValue 可选,映射函数(mapFunction)中的 this 对象。

原文链接:blog.csdn.net/hkduan/arti…