本质就是将伪数组转为数组进行使用

1.转换 arguments 对象

function sum() {
  const args = Array.from(arguments);
  return args.reduce((acc, num) => acc + num, 0);
}

console.log(sum(1, 2, 3)); // 输出 6

2.转换 DOM 集合

const divs = document.querySelectorAll('div');
const divArray = Array.from(divs);
divArray.forEach(div => console.log(div.textContent));

3.生成长度为 5 的数组

const arr = Array.from({ length: 5 }, (_, index) => index + 1);
console.log(arr); // 输出 [1, 2, 3, 4, 5]

4.处理可迭代对象

const set = new Set([1, 2, 3]);
const array = Array.from(set);
console.log(array); // 输出 [1, 2, 3]
const str = 'hello';
const chars = Array.from(str);
console.log(chars); // 输出 ['h', 'e', 'l', 'l', 'o']

5.结合映射函数处理元素

const numbers = [1, 2, 3];
const squares = Array.from(numbers, num => num ** 2);
console.log(squares); // 输出 [1, 4, 9]

6.与 Array.prototype.slice.call() 的对比

我们发现更加使用一些,简介一些用Array.from()

const args = Array.prototype.slice.call(arguments);

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐