作用:

Array.from() 方法从一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。

语法:

Array.from(object, mapFunction, thisValue)
  • object,必需,要转换为数组的对象。
  • mapFunction,可选,数组中每个元素要调用的函数。
  • thisValue,可选,映射函数(mapFunction)中的 this 对象。

实例:

//1、从 String 生成数组
Array.from('foo');
// [ "f", "o", "o" ]

//2、从 Set 生成数组:去重
const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);
// [ "foo", "bar", "baz" ]

//3、从 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'];

拓展:

//在 Array.from 中使用箭头函数
Array.from([1, 2, 3], x => x + x);
// [2, 4, 6]
Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]

William_Wang
21 声望1 粉丝