语法:Array.from(arrayLike[, mapFn[, thisArg]])
返回值:一个新的数组实例。
Array.from()
方法对一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。
arrayLike
想要转换成数组的伪数组对象或可迭代对象。mapFn
可选如果指定了该参数,新数组中的每个元素会执行该回调函数。thisArg
可选可选参数,执行回调函数 mapFn
时 this
对象。
从String生成数组
Array.from('foo');// [ "f", "o", "o" ]
从Set生成数组
const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);// [ "foo", "bar", "baz" ]
从Map生成数组
const map = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(map);
// [[1, 2], [2, 4], [4, 8]]
const mapper = new Map([['1', 'a'], ['2', 'b']]);
Array.from(mapper.values());
// ['a', 'b'];
Array.from(mapper.keys());
// ['1', '2'];
从类数组对象(arguments)生成数组
function f() {
return Array.from(arguments);
}
f(1, 2, 3); // [ 1, 2, 3 ]
在Array.from()
使用箭头函数
// Using an arrow function as the map function to
// manipulate the elements
Array.from([1, 2, 3], x => x + x);
// [2, 4, 6]
// Generate a sequence of numbers
// Since the array is initialized with `undefined` on each position,
// the value of `v` below will be `undefined`
Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]
数组去重合并
function combine(){
let arr = [].concat.apply([], arguments); //没有去重复的新数组
return Array.from(new Set(arr));
}
var m = [1, 2, 2], n = [2,3,3];
console.log(combine(m,n));// [1, 2, 3]