JavaScript中Array.from()的用法總結(jié)
前言
這個方法認識很久了,也使用過,卻一直稀里糊涂的,今天帶大家從頭認識一下。
官方解釋:The Array.from() static method creates a new, shallow-copied Array instance from an iterable or array-like object.
注意: an iterable / array-like object
語法
Array.from(arrayLike) Array.from(arrayLike, mapFn) Array.from(arrayLike, mapFn, thisArg)
參數(shù)
- arrayLike:想要轉(zhuǎn)換成數(shù)組的類數(shù)組或可迭代對象。類數(shù)組對象(帶有 length 屬性和索引元素的對象)。
- mapFn 可選:調(diào)用數(shù)組每個元素的函數(shù)。如果提供,每個將要添加到數(shù)組中的值首先會傳遞給該函數(shù),然后將 mapFn 的返回值增加到數(shù)組中。使用以下參數(shù)調(diào)用該函數(shù):
- element:數(shù)組當前正在處理的元素。
- index:數(shù)組當前正在處理的元素的索引。
- thisArg 可選:執(zhí)行 mapFn 時用作 this 的值。
返回值
一個新的數(shù)組實例。
使用
字符串
Array.from("foo"); // [ "f", "o", "o" ]
Set
const set = new Set(["foo", "bar", "baz", "foo"]); Array.from(set); // [ "foo", "bar", "baz" ]
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'];
注意 new Map() 和 {} 的區(qū)別
const map = { ? ? 0: 1, ? ? 1: 2, ? ? 3: 4, } let result = Array.from(map) console.log(result) // []
給 map 對象加個 length
const map = { ? ? 0: 1, ? ? 1: 2, ? ? 3: 4, ? ? length: 3 } let result = Array.from(map) console.log(result) // [ 1, 2, undefined ]
將 length 改為 4
console.log(result) // [ 1, 2, undefined, 4 ]
加上 length 就是類數(shù)組對象,Array.from() 默認從下標0查找并加入新數(shù)組中。上面的Array.from() 省略了 mapFn ,其實和下面的是一樣的。
let result = Array.from(map, (v, i) => v)
這樣更加醒目,Array.from 是通過 length 屬性去遍歷、然后取值加入到新數(shù)組中的。
NodeList
// 根據(jù) DOM 元素的屬性創(chuàng)建一個數(shù)組 const images = document.querySelectorAll("img"); const sources = Array.from(images, (image) => image.src); const insecureSources = sources.filter((link) => link.startsWith("http://"));
箭頭函數(shù)
// 使用箭頭函數(shù)作為映射函數(shù)去 // 操作多個元素 Array.from([1, 2, 3], (x) => x + x); // [2, 4, 6] // 生成一個數(shù)字序列 // 因為數(shù)組在每個位置都使用 `undefined` 初始化, // 下面的 `v` 值將是 `undefined` Array.from({ length: 5 }, (v, i) => i); // [0, 1, 2, 3, 4]
稀疏數(shù)組
console.log(Array.from([,,3,4])) // [ undefined, undefined, 3, 4 ]
序列生成器
// 序列生成器函數(shù)(通常稱為“range”,例如 Clojure、PHP 等) const range = (start, stop, step) => ? Array.from({ length: (stop - start) / step + 1 }, (_, i) => start + i * step); // 生成的數(shù)字范圍 0..4 range(0, 4, 1); // [0, 1, 2, 3, 4] // 生成的數(shù)字范圍 1..10,步長為 2 range(1, 10, 2); // [1, 3, 5, 7, 9] // 使用 Array.from 生成字母表,并將其序列排序 range("A".charCodeAt(0), "Z".charCodeAt(0), 1).map((x) => ? String.fromCharCode(x), ); // ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
在非數(shù)組構(gòu)造函數(shù)上調(diào)用 from()
from() 方法可以在任何構(gòu)造函數(shù)上調(diào)用,只要該構(gòu)造函數(shù)接受一個表示新數(shù)組長度的單個參數(shù)。
function NotArray(len) { ? console.log("NotArray called with length", len); } // 可迭代對象 console.log(Array.from.call(NotArray, new Set(["foo", "bar", "baz"]))); // NotArray called with length undefined // NotArray { '0': 'foo', '1': 'bar', '2': 'baz', length: 3 } // 類數(shù)組對象 console.log(Array.from.call(NotArray, { length: 1, 0: "foo" })); // NotArray called with length 1 // NotArray { '0': 'foo', length: 1 }
當 this 值不是構(gòu)造函數(shù),返回一個普通的數(shù)組對象。
console.log(Array.from.call({}, { length: 1, 0: "foo" })); // [ 'foo' ]
與 Array.map() 區(qū)別
Array.from(obj, mapFn, thisArg) 和 Array.from(obj).map(mapFn, thisArg) 具有相同的結(jié)果,只是它不會創(chuàng)建中間數(shù)組,并且 mapFn 僅接受兩個參數(shù)(element、index),不接受數(shù)組,因為數(shù)組仍然在構(gòu)建中。
Array.map(mapFn, thisArg)參數(shù) mapFn 接受三個參數(shù)(element、index、array),array為調(diào)用了 map() 的數(shù)組本身。
Array.from()基本可替代 Array.map() 方法。
總結(jié)
Array.from(arrayLike, mapFn, thisArg) 接受三個參數(shù),后二個參數(shù)為可選參數(shù),并返回一個數(shù)組實例。并且該數(shù)組實例不是稀疏數(shù)組。
Array.from()可直接從可迭代對象上返回一個新的數(shù)組。如:String、Map、Set。
const map = { ? ? 0: 1, ? ? 1: 2, ? ? 3: 4, ? ? length: 3 } console.log(Symbol.iterator in map) // false console.log(Symbol.iterator in new String('1123')) // true console.log(Symbol.iterator in new Map()) // true console.log(Symbol.iterator in new Set()) // true
Array.from()也可以從類數(shù)組對象上返回一個新數(shù)組。
Array.from({ length: 5 }, (v, i) => i); // [0, 1, 2, 3, 4]
Array.from()基本可替代 Array.map() 方法。
參考
Array.from() - JavaScript | MDN (mozilla.org)
到此這篇關于JavaScript中Array.from()的用法總結(jié)的文章就介紹到這了,更多相關JavaScript Array.from()內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!