likes
comments
collection
share

Array.from()的用法总结

作者站长头像
站长
· 阅读数 11

前言

这个方法认识很久了,也使用过,却一直稀里糊涂的,今天带大家从头认识一下。

官方解释: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)

参数

  • arrayLike

    想要转换成数组的类数组或可迭代对象。类数组对象(带有 length 属性和索引元素的对象)。

  • mapFn 可选

    调用数组每个元素的函数。如果提供,每个将要添加到数组中的值首先会传递给该函数,然后将 mapFn 的返回值增加到数组中。使用以下参数调用该函数:

    • element

      数组当前正在处理的元素。

    • index

      数组当前正在处理的元素的索引。

  • thisArg 可选

    执行 mapFn 时用作 this 的值。

返回值

一个新的数组实例。

使用

字符串

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(){} 的区别

const map = {
    0: 1,
    1: 2,
    3: 4,
}

let result = Array.from(map)

console.log(result) // [],这里的map不是一个可迭代对象,也不是类数组对象

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 就是类数组对象,Array.from() 默认从下标0查找并加入新数组中。上面的Array.from() 省略了 mapFn ,其实和下面的是一样的。

let result = Array.from(map, (v, i) => v)

这样更加醒目,Array.from 是通过 length 属性去遍历、然后取值加入到新数组中的。

NodeList

// 根据 DOM 元素的属性创建一个数组
const images = document.querySelectorAll("img");
const sources = Array.from(images, (image) => image.src);
const insecureSources = sources.filter((link) => link.startsWith("http://"));

箭头函数

// 使用箭头函数作为映射函数去
// 操作多个元素
Array.from([1, 2, 3], (x) => x + x);
// [2, 4, 6]

// 生成一个数字序列
// 因为数组在每个位置都使用 `undefined` 初始化,
// 下面的 `v` 值将是 `undefined`
Array.from({ length: 5 }, (v, i) => i);
// [0, 1, 2, 3, 4]

稀疏数组

console.log(Array.from([,,3,4])) // [ undefined, undefined, 3, 4 ]

序列生成器

// 序列生成器函数(通常称为“range”,例如 Clojure、PHP 等)
const range = (start, stop, step) =>
  Array.from({ length: (stop - start) / step + 1 }, (_, i) => start + i * step);

// 生成的数字范围 0..4
range(0, 4, 1);
// [0, 1, 2, 3, 4]

// 生成的数字范围 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"]

在非数组构造函数上调用 from()

from() 方法可以在任何构造函数上调用,只要该构造函数接受一个表示新数组长度的单个参数。

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 }

// 类数组对象
console.log(Array.from.call(NotArray, { length: 1, 0: "foo" }));
// NotArray called with length 1
// NotArray { '0': 'foo', length: 1 }

当 this 值不是构造函数,返回一个普通的数组对象。

console.log(Array.from.call({}, { length: 1, 0: "foo" })); // [ 'foo' ]

Array.map() 区别

Array.from(obj, mapFn, thisArg) 和 Array.from(obj).map(mapFn, thisArg) 具有相同的结果,只是它不会创建中间数组,并且 mapFn 仅接受两个参数(elementindex),不接受数组,因为数组仍然在构建中。

Array.map(mapFn, thisArg)参数 mapFn 接受三个参数(elementindexarray),array为调用了 map() 的数组本身。

Array.from()基本可替代 Array.map() 方法。

总结

  • Array.from(arrayLike, mapFn, thisArg) 接受三个参数,后二个参数为可选参数,并返回一个数组实例。并且该数组实例不是稀疏数组。
  • Array.from()可直接从可迭代对象上返回一个新的数组。如: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()也可以从类数组对象上返回一个新数组。
    Array.from({ length: 5 }, (v, i) => i); // [0, 1, 2, 3, 4]
    
  • Array.from()基本可替代 Array.map() 方法。

参考

Array.from() - JavaScript | MDN (mozilla.org)