[].slice.call(document.querySelectorAll(‘li‘), 0):类数组转数组

本文介绍了JavaScript中类数组对象的概念,如arguments和DOM查询结果,它们拥有length属性但缺少数组的方法。文章通过实例解释了如何将类数组转换为真正的数组,包括使用Array.prototype.slice.call()和ES6的扩展运算符及Array.from()方法。重点讨论了类数组与数组之间的区别,并提供了相关参考链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

今天看到一句这样的代码:

[].slice.call(document.querySelectorAll('li'), 0)

这是在干嘛?没看懂。搜了一下,大家说,这是在把DOM节点数组转为真正的数组。哦~ 我想起来了,好像是有这么回事,selector 返回的数组好像是叫「类数组」来着。

什么是类数组

类数组又叫伪数组,是形似数组,但不是数组的类数组对象。函数的 arguments 参数,以及 DOM 元素查找方法返回的 nodeList 对象都属于类数组。

类数组和数组的区别

类数组:有遍历方法、有 length 属性,但没有其他数组方法。

//类数组
const nodeList = document.querySelectorAll('li')
nodeList.__proto__

//数组
const list = [].slice.call(document.querySelectorAll('li'), 0)
list.__proto__

nodeList instanceof Array  //false
list instanceof Array  	   //true

通过输出原型我们可以看到,nodeList 的原型上只有几个遍历方法和 length 属性。

在这里插入图片描述

数组的原型链:list → Array.prototype → Object.prototype → null
nodeList 的原型链:nodeList → NodeList.prototype → Object.prototype → null

类数组转数组

除了上述 [].slice.call(document.querySelectorAll('li'), 0) 的方法以外,ES6 提供了更简便的方式:

  • 使用扩展运算符 ...
const newList = [...nodeList]
newList instanceof Array  //true
  • 使用 Array.from() 方法
const newList = Array.from(nodeList)
newList instanceof Array  //true

参考链接

https://developer.mozilla.org/zh-CN/docs/Web/API/NodeList

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值