es6 Set 结合 Array.from 用法

Array.from的设计初衷是快速便捷的基于其他对象创建新数组,准确来说就是从一个类似数组的可迭代对象( Object、Array、StringSetMaparguments等 )创建一个新的数组实例,说人话就是,只要一个对象有迭代器,Array.from就能把它变成一个数组

Array.from() 方法接受类数组对象以及可迭代对象,它可以接受一个 map 函数,并且,这个 map 函数不会跳过值为 undefined 的数值项

var arr=[1,2,3,2,3,4,5];   

var set=new Set(arr)

var arr1=Array.from(set)

 

重复数组  -  Set 化 (去重) 转回数组

上述代码,实现数组去重,省去了传统实现中的循环算法

 

其它用法:

1 类数组转数组

Array.from('Hey');                   // => ['H', 'e', 'y']
Array.from(new Set(['one', 'two'])); // => ['one', 'two']

const map = new Map();
map.set('one', 1)
map.set('two', 2);
Array.from(map); // => [['one', 1], ['two', 2]]
View Code

 

2 拷贝数组

2.1  浅拷贝

const numbers = [3, 6, 9];
const numbersCopy = Array.from(numbers);

numbers === numbersCopy; // => false
View Code

2.2 深拷贝

function recursiveClone(val) {
    return Array.isArray(val) ? Array.from(val, recursiveClone) : val;
}

const numbers = [[0, 1, 2], ['one', 'two', 'three']];
const numbersClone = recursiveClone(numbers);

numbersClone; // => [[0, 1, 2], ['one', 'two', 'three']]
numbers[0] === numbersClone[0] // => false
View Code

 

3 初始化数组   Array.from({length: 10}, (v, i) => i); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

const length = 3;
const init   = 0;
const result = Array.from({ length }, () => init);
View Code

 

4 生成范围数组

function range(end) {
    return Array.from({ length: end }, (_, index) => index);
}

range(4);
View Code
posted @ 2019-04-24 14:15  justSmile2  阅读(972)  评论(0编辑  收藏  举报