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

作用:

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]

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理