Array.from()

79 阅读1分钟

函数特点

  • arrayLike - 伪数组对象【字符串,NodeList,arguments】或可迭代对象【Set,Map】
  • mapFn - 新数组中每个元素都会执行该回调函数
  • thisArg - 执行回调函数mapFn时this对象
  • 返回值 - 新数组实例
  • 若参数是一个真正的数组,则会返回一个一模一样的新数组【浅拷贝】

函数用法

Array.from(arrayLike, mapFn, thisArg)

使用场景

  • 对现有的数组进行浅拷贝
const ary = [{ name: 'abc' }];
const copyAry = Array.from(ary);
copyAry[0].name = 'abcd';
console.log(ary); // [{ name: 'abcd }]
  • 用于将类数组结构组实例【必须有length属性】
// 字符串【字符串会被拆分为单字符数组】
Array.from('abc'); // ['a', 'b', 'c']

// Map
const m = new Map().set(1, 2).set(3, 4);
Array.from(m); // [[1, 2], [3, 4]]

// Set
const s = new Set().add(1).add(2).add(3).add(4);
Array.from(s); // [1, 2, 3, 4]

// 可迭代对象
const aryList = {};

// NodeList对象
cosnt nodes = document.querySelectorAll('li');
Array.from(nodes); // [<li>...</li>]

// arguments对象
function fn() {
    return Array.from(arguments); 
}
fn(1, 2, 3); // [1, 2, 3]