1. 基本语法
语法:Array.from(类数组[, 回调函数[, 参数]])
说明:
- 类数组:转换成数组的类似数组或可迭代的对象
- 回调函数:可选参数,如果加了这个参数,表示数组中的元素都要执行这个回调函数
- 参数:可选,执行回调函数时的this对象
2. 字符串转数组
let a = Array.from(123456789);
let b = Array.from("123456789");
console.log(a);
console.log(b);
结果:
[]
["1", "2", "3", "4", "5", "6", "7", "8", "9"]
说明:不能将数值类型的元素直接转换成数组,即使调用Array.from()方法,返回的结果也只是一个空数组
2. 将Map转换成数组
let map = new Map([['1','2'],['5','6'],['9','10']])
let mnc = Array.from(map);
console.log(mnc);
结果:
[Array(2), Array(2), Array(2)]
0: (2) ["1", "2"]
1: (2) ["5", "6"]
2: (2) ["9", "10"]
3. 将Set转换成数组
let set = new Set([1,3,1,3,2,4,5,6]);
let cbn = Array.from(set);
console.log(cbn);
结果:
[1, 3, 2, 4, 5, 6]
4. 将函数参数转数组
function func(){
return Array.from(arguments);
}
let params = func(11,22,33,44,55,66,77,88,99);
console.log(params);
结果:
[11, 22, 33, 44, 55, 66, 77, 88, 99]
5. 箭头函数转数组
let a = Array.from([11,22,33,44,55,66,77,88,99],w => w * w * w);
console.log(a);
let b = Array.from({length:50},(m,k) => k);
console.log(b);
结果:
[1331, 10648, 35937, 85184, 166375, 287496, 456533, 681472, 970299]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
6. 数组去重合并
function filterArr(){
let array = [].concat.apply([], arguments);
let set = new Set(array);
return Array.from(set);
}
let a1 = [1,2,4,5,6,7,8,0,2,3,4,12,6,7,9];
let a2 = [4,57,8,2,1,2,34,56,89,45,21,3,4];
let a0 = filterArr(a1,a2);
let b0 = filterArr(a2,a1);
console.log(a0);
console.log(b0);
结果:
[1, 2, 4, 5, 6, 7, 8, 0, 3, 12, 9, 57, 34, 56, 89, 45, 21]
[4, 57, 8, 2, 1, 34, 56, 89, 45, 21, 3, 5, 6, 7, 0, 12, 9]
网友评论