Array.from()和Array.of()用法

Array.from()和Array.of()是ES6新增的两个用于创建数组的静态方法。

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

语法

1 Array.from(arrayLike[, mapFn[, thisArg]])

参数

arrayLike:是一个类数组对象,即任何可迭代的结构,或者有一个length属性和可索引元素的结构

mapFn:可选,如果指定了该参数,新数组中的每个元素会执行该回调函数

thisArg:可选,执行回调函数mapFn时this对象。但这个重写的this值在箭头函数中不适用。

返回值

一个新的数组实例

示例:

1.从String生成数组

1 Array.from('foo');
2 //["f", "o", "o"]

2.从Set生成数组

1 const set = new Set(['foo', 'bar', 'baz', 'foo']);
2 Array.from(set);
3 //['foo', 'bar', 'baz']

3.从Map生成数组

 1 const map = new Map([[1, 2], [2, 4], [4, 8]]);
 2 Array.from(map);
 3 //[[1, 2], [2, 4], [4, 8]]
 4 
 5 const mapper = new Map([['1', 'a'], ['2', 'b']]);
 6 Array.from(mapper.values());
 7 //['a', 'b'];
 8 
 9 Array.from(mapper.keys());
10 //['1', '2'];

4.从类数组对象(arguments)生成数组

 1 function f() {
 2     return Array.from(arguments);
 3 }
 4 
 5 f(1, 2, 3);
 6 
 7 //[1, 2, 3]
 8 //也能转换带有必要属性的自定义对象
 9 const arrayLikeObject = {
10     0: 1,
11     1: 2,
12     2: 3,
13     3: 4,
14     length: 4
15 };
16 console.log(Array.from(arrayLikeObject));   //[1, 2, 3, 4]

4.对现有数组执行浅复制

1 const a1 = [1, 2, 3, 4]
2 const a2 = Array.from(a1);
3 
4 console.log(a1);   //[1, 2, 3, 4]
5 alert(a1 === a2);   //false

5.在Array.from()中使用箭头函数

 1 //Using an arrow function as the map function to manipulate the elements
 2 
 3 Arrray.from([1, 2, 3, 4], x => x + x);
 4 //[2, 4, 6, 8]
 5 
 6 
 7 //Generate a sequence of numbers, Since the array is initialized with 'undefined' on each positions, the value of 'v' below will be 'undefined'
 8 
 9 Array.from({length: 5}, (v, i) => i)
10 //[0, 1, 2, 3, 4]

5.数组去重合并

1 function combine() {
2     let arr = [].concat.apply([], arguments);   //没有去重复的新数组
3     return Array.from(new Set(arr));
4 }
5 
6 var m = [1, 2, 2], n = [2, 3, 3];
7 console.log(combine(m, n));   //[1, 2, 3]

 Array.of()方法创建一个具有可变数量参数的新数组实例,而不考虑参数的数量或类型。用于替代在ES6之前常用的Array.prototype.slice.call(arugments)。

语法

1 Array.of(element0[, element1[, ...[, elementN]]])

参数

elementN:任意个参数,将按顺序成为返回数组中的元素

返回值

新的Array实例

示例

1 Array.of(1);   //[1]
2 Array.of(1, 2, 3);  //[1, 2, 3]
3 Array.of(undefined);   //[undefined]

兼容旧环境

如果原生不支持的haul,在其他代码之前执行以下代码会创建Array.of()。

1 if(!Array.of) {
2     Array.of = function() {
3         return Array.prototype.slice.call(arguments);
4     };
5 }

Array.of()与Array构造函数之间的区别在于处理整数参数:Array.of(7)创建一个具有单个元素7的数组,而Array(7)创建一个长度为7的空数组(注:这里指一个有7个空位(empty)的数组,而不是由7个undefined组成的数组)。

原文地址:https://www.cnblogs.com/sparkler/p/13748602.html