Array.from()
Array.from({ length: 5 }, _ => 0)
// [0,0,0,0,0]
含义:
计算出length为5,每一项均为0的数组
基本用法
- 可用作数组递增
function range(ends) {
return Array.from({length: ends}, (_, i) => i + 1)
}
console.log(range(3)); // [1, 2, 3]
- 可以将Unicode编码拆解成数组
console.log(Array.from('\u6211\u7231\u6572\u4ee3\u7801'))
//(5) ["我", "爱", "敲", "代", "码"]
- 将类数组转换为数组
let array = {
0: 'name',
1: 'age',
2: 'sex',
3: ['user1','user2','user3'],
'length': 4
}
let arr = Array.from(array )
console.log(arr) // ['name','age','sex',['user1','user2','user3']]
ps: new Set 用法
- 将数组解构成伪数组
new Set([1,2,3,4,5])
// Set(5) {1, 2, 3, 4, 5}
- ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值
new Set([1,2,2,3,3,4])
// Set(5) {1, 2, 3, 4}
将数组使用new Set方法转换成不重复的伪数组,再使用Array.from方法,可以方便的实现数组去重