每天做个总结吧,坚持就是胜利!
/**
@date 2021-06-10
@description 类数组转化为数组
*/
壹(序)
类数组是具有length属性,而且键名从0开始递增,但是原型上没有数组的相关方法,比如arguments,NodeList等,都是类数组;今天总结将类数组转换为数组的几种方法。
贰(方法)
公共代码:
const nodeList = document.querySelectorAll('body'); // NodeList [body]
- 使用
Array.from();
const arr = Array.from(nodeList); // [body]
- 使用
扩展运算符;
const arr = [...nodeList]; // [body]
- 使用
Array.prototype.concat();
const arr = Array.prototype.concat.call(str); // [body]
- 使用
Array.prototype.slice();
const arr = Array.prototype.concat.apply([], str); // [body]