类数组转化为数组

825 阅读1分钟

每天做个总结吧,坚持就是胜利!

    /**
        @date 2021-06-10
        @description 类数组转化为数组
    */

壹(序)

类数组是具有length属性,而且键名0开始递增,但是原型上没有数组的相关方法,比如argumentsNodeList等,都是类数组;今天总结将类数组转换为数组的几种方法。

贰(方法)

公共代码:

const nodeList = document.querySelectorAll('body'); // NodeList [body]
  1. 使用Array.from();
const arr = Array.from(nodeList); // [body]
  1. 使用扩展运算符
const arr = [...nodeList]; // [body]
  1. 使用Array.prototype.concat()
const arr = Array.prototype.concat.call(str); // [body]
  1. 使用Array.prototype.slice();
const arr = Array.prototype.concat.apply([], str); // [body]