Array-Like Objects 详解

什么是 Array-Like Objects

顾名思义, 就是 类数组的对象。类数组对象具备数组的属性length,可是没有 数组 的一些方法, 好比 push。以下javascript

const arrayLike = {
  0: "1",
  1: "2",
  length: 2
}

好比 arguments 就是一个 Array-Like Objects。java

function sum() {
  console.log(arguments)
}

sum( 1, 2, 3 )

image.png
看起来是一个数组,但咱们能够看见上面截图中的 arguments 的隐式原型 arguments._ _proto__ 中的方法和数组确实不同的。
咱们来看看一个正常的数组的隐式原型是啥样的。
image.png
截图只展现了一部分,可是咱们能够看见有明显的不一样,因此说 arguments是一个 类数组对象 Array-Like Objects。
此时咱们对 arguments 这个类数组对象进行 push 等数组的操做是会报错的。
image.png
那么咱们怎么将 array-like 转换成 array 呢?es6

Array-Like 转 Array

方法一: 遍历迭代

由于 Array-Like Objects 是有长度的,因此咱们能够对其进行遍历, 将其每个元素塞进新的数组数组

function sum() {
  let arr = []
  for(let i = 0; i < arguments.length; i++) {
    arr.push(arguments[i])
  }
  arguments = arr
  arguments.push(4) // 此时的 argument 已是数组了,能够进行数组的 push 操做
  console.log(arguments) // [ 1, 2, 3, 4 ]
} 
sum( 1, 2, 3 )

方法二: 使用 Array.prototype.slice.call()

function sum() {
  arguments = Array.prototype.slice.call(arguments);
  //  arguments = [].slice.call(arguments);
  arguments.push(4) // 此时的 arguments 已是数组了,能够进行数组的 push 操做
  console.log(arguments) // [ 1, 2, 3, 4 ]
} 
sum( 1, 2, 3 )

同理,使用 Array.prototype.slice.apply()、Array.prototype.slice.bind() 也是同样的。app

方法三: Array.from()

function sum() {
  arguments = Array.from(arguments);
  arguments.push(4); // 此时的 arguments 已是数组了,能够进行数组的 push 操做
  console.log(arguments); // [ 1, 2, 3, 4 ]
} 

sum( 1, 2, 3 )

补充:
评论区小伙伴提出的 es6 解构也能实现,更简洁优雅spa

function sum() {
  arguments = [ ...arguments];
  arguments.push(4); // 此时的 arguments 已是数组了,能够进行数组的 push 操做
  console.log(arguments); // [ 1, 2, 3, 4 ]
} 

sum( 1, 2, 3 )
相关文章
相关标签/搜索