21、类数组转数组

73 阅读1分钟

什么是类数组?

一种具备数组结构,但不支持数组方法的数据结构

核心是支持数字索引与length属性,但不是通过Array创建的,所以不具备数组方法

常见的类数组有哪些?

Arguments

function 定义的函数内部的关键词,包含所有的参数。

原型链:myArguments --> Arguments.prototype --> Object.prototype --> null

callee指向函数本身

length调用函数时传参数量

支持使用for、for...of、for...in、Object.keys、对象方法来循环

Arguments 对象 - JavaScript | MDN

NodeList

通过ducment.querySelectorAll获取到的 DOM 列表

原型链:myNodeList --> NodeList.prototype --> Object.prototype --> null

length子节点数量

支持使用for、for...of、Object.keys、对象方法、forEach来循环

NodeList - Web API 接口参考 | MDN

HTMLCollection

通过ducment.getElementsByTagName获取到的 DOM 列表

原型链:myHTMLCollection --> HTMLCollection.prototype --> Object.prototype --> null

length子节点数量

支持使用for、for...of、Object.keys、对象方法来循环

HTMLCollection - Web API 接口参考 | MDN

String

有 length,可通过下标取值,不支持数组方法,这完全跟类数组的特点一致

类数组如何转为数组呢?

Array.from

作用:从可迭代类数组对象创建一个新的浅拷贝的数组实例。

原理:是基于传入数据的 length 属性以及通过索引访问元素的能力,将元素添加到新数组

const arr1 = Array.from(arguments)
const arr2 = Array.from(NodeList)
const arr3 = Array.from(HTMLCollection)

Array.from() - JavaScript | MDN

... 解构

const arr1 = [...arguments]
const arr2 = [...NodeList]
const arr3 = [...HTMLCollection]

Array.prototype.slice.call

slice:是基于传入对象的 length 属性以及通过索引访问元素的能力,实现复制元素并返回新数组

const arr1 = Array.prototype.slice.call(arguments)
const arr2 = Array.prototype.slice.call(NodeList)
const arr3 = Array.prototype.slice.call(HTMLCollection)

[].slice.call

本质还是借用 slice 实现

const arr1 = [].slice.call(arguments)
const arr2 = [].slice.call(NodeList)
const arr3 = [].slice.call(HTMLCollection)