Common pseudo-arrays: Arguments, getElementsByTagName, etc. get NodeList objects

Pseudo-arrays have the following characteristics:

  • Has the length property
  • Store data by index
  • You can’t use array methods like push(), pop(), etc

The essence is an object type, and the prototype points to Obejct

function hello () {
  console.log(Object.prototype.toString.call(arguments))  // '[object Arguments]''
  console.log(typeof arguments) // 'object'
  console.log(arguments.__proto__.constructor === Object) // true
}
hello(1.2)
Copy the code

Method of converting a pseudo-array to an array

1, the Array. The from ()
function hello() {
  console.log(arguments) // Arguments(3)
                         // 0: 1
                         // 1: 2
                         // 2: 3
                         / / the callee: ƒ hello ()
                         // length: 3
                         / / Symbol (Symbol. The iterator) : ƒ values ()
                         // __proto__: Object
  let arr = Array.from(arguments)
  console.log(arr) // Array(3)
                   // 0: 1
                   // 1: 2
                   // 2: 3
                   // length: 3
                   // __proto__: Array(0)
}
hello(1.2.3)
Copy the code
2, Array. Prototype. Slice. The call ()
function hello() {
  let arr = Array.prototype.slice.call(arguments)
  console.log(arr) / / [1, 2, 3]
                   // 0: 1
                   // 1: 2
                   // 2: 3
                   // length: 3
                   // __proto__: Array(0)
}
hello(1.2.3)
Copy the code
3. Expand operators
function hello() {
  let arr = [...arguments]
  console.log(arr) / / [1, 2, 3]
                   // 0: 1
                   // 1: 2
                   // 2: 3
                   // length: 3
                   // __proto__: Array(0)
}
hello(1.2.3)
Copy the code