关于javascript:Arrayfrom方法通过给定的对象中创建一个数组

21次阅读

共计 633 个字符,预计需要花费 2 分钟才能阅读完成。

作用:

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]

正文完
 0