优雅使用Array.from

199 阅读1分钟

前言

Array.fromES6新增的一个方法

Array.from

要求传入一个类数组可迭代对象的参数,创建一个新的浅拷贝的数组。

console.log(Array.from('a string')) 
// 输出:["a", " ", "s", "t", "r", "i", "n", "g"]

console.log(Array.from(new Set(['apple','orange','banana'])) 
// 输出:['apple','orange','banana']

console.log(Array.from(new Map([[1,'one'],[2,'two'],[3,'three']])))
// 输出:[[1,'one'],[2,'two'],[3,'three']]

使用技巧

快速初始化填充数组

const length = 3;
const init   = 1;
const result = Array.from({ length }, () => init)
console.log(result)
// 输出:[1,1,1]

快速获取范围内数组

const range = (start, end, step = 1) => Array.from({ length: (end - start) / step + 1}, (_, i) => start + (i * step))
console.log(range(1,4)) 
// 输出: [1, 2, 3, 4]

快速去重数组

const unique = (arr) => Array.from(new Set(arr));
console.log(unique([1,2,3,2])) // 输出:[1,2,3]
console.log(unique(['a','b','a','c'])) // 输出:['a','b','c']

总结

上面的写法,还有更多方法去实现。只希望各位能给各位提供一些帮助和自己的记录。