本篇文章參考以下博文
文章目錄
一、前言
最近在使用 Set 對象去重的時候,發現 from 函數的一些用法,感覺可以挖掘深入一些,所以寫此文章總結記錄,方便以後複習查看。
二、定義
from 方法用於通過擁有 length 屬性的對象或可迭代的對象來返回一個數組。
三、語法
Array.from(object, mapFunction, thisValue)
- object 要轉化成數組的對象
- mapFunction 數組中每個元素要調用的函數
- thisValue 設置 mapFunction 中的 this 對象
四、實例
4.1 結合 Set 去重
這個方法最常用的應該就是配合 Set 對象,進行去重,寫法如下:
Array.from(new Set(arr));
4.2 從 String 生成數組
Array.from('foo');
// [ "f", "o", "o" ]
4.3 從 Set 生成數組
const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);
// [ "foo", "bar", "baz" ]
4.4 從 Map 生成數組
不光可以把 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'];
4.5 從類數組對象(arguments)生成數組
function f() {
return Array.from(arguments);
}
f(1, 2, 3);
// [ 1, 2, 3 ]
4.6 拷貝數組
淺拷貝
const numbers = [1, 2, 3];
const numbersCopy = Array.from(numbers);
深拷貝,下面是通過 from 的第二個參數 對數組元素循環調用。
function recursiveClone(val) {
return Array.isArray(val) ? Array.from(val, recursiveClone) : val;
}
4.7 初始化數組
Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]
/****************************/
const result = Array.from({ length:3 }, () => 1);
result; // => [1, 1, 1]
/****************************/
const resultA = Array.from({ length:3 }, () => ({}));
result; // => [{}, {}, {}]