LinDaiDai/niubility-coding-js

🎁第7期第2题:转换类数组的几种方式

Opened this issue · 0 comments

转换类数组的几种方式

类数组概念

拥有length属性和若干索引属性的对象就被称为类数组,它和数组类似,但是不能调用数组的方法。

常见类数组:

DOM方法返回的批量的DOM集合, arguments,另外函数也可以被看为是类数组,因为它拥有length属性,length的值就是它可接收的参数的个数。

转换为数组

先让我们来定义一个类数组:

function test () {
  console.log(Array.isArray(arguments)) // false
}
test('霖', '呆', '呆')

然后来看看可以有哪几种转换方法:

  1. 通过call和数组的slice方法:
[].slice.call(arguments)

// 当然也可以是这样,因为slice是Array.prototype上的方法

Array.prototype.slice.call(arguments)
  1. 通过call和数组的splice方法:
[].splice.call(arguments)
  1. 通过apply和数组的concat方法:
[].concat.apply(arguments)
  1. 通过Array.from()
Array.from(arguments)
  1. ...展开操作符:
[...arguments]

来写个简写吧:

  • slice + call
  • splice + call
  • concat + apply
  • Array.from
  • ...

不过貌似这个不用特意去记,想一下数组有哪些方法可以用基本就能想起来了。