CastArray converts the first argument passed in to an array as an array literal, or returns it if it is already an array. The source code is very simple, as follows:

function castArray(. args) {
  // An empty array is returned when arguments are not passed
  if(! args.length) {return[]}// Get the first argument
  const value = args[0]
  If it is already an array, it returns itself, if not, it returns an array literal wrapped around it
  return Array.isArray(value) ? value : [value]
}
Copy the code

Array.of

The array.of () method creates a new Array instance from a variable number of arguments, regardless of the number or type of arguments.

console.log(castArray(1)) / / [1]
console.log(castArray(null)) // [null]
console.log(castArray(undefined)) // [undefined]
console.log(castArray(1.2.3)) / / [1]
console.log(castArray({a: 1.b: 2})) // [{a: 1, b: 2}]
console.log(castArray([1.2.3])) / / [1, 2, 3]
const array = [1.2.3]
console.log(castArray(array) === array) // => true

console.log(Array.of(1)) / / [1]
console.log(Array.of(null)) // [null]
console.log(Array.of(undefined)) // [undefined]
console.log(Array.of(1.2.3)) / / [1, 2, 3]
console.log(Array.of({a: 1.b: 2})) // [{a: 1, b: 2}]
console.log(Array.of([1.2.3])) / / [[1, 2, 3]]
Copy the code

The above results can be seen as follows:

  • castArrayThe function does not support converting multiple arguments to arrays
  • For parameters that are themselves arrays,castArrayThe function returns the array directly

new Array

console.log(new Array(1)) // [<1 empty item>] passes a numeric argument to create a sparse array with length n
console.log(new Array(null)) // [null]
console.log(new Array(undefined)) // [undefined]
console.log(new Array(1.2.3)) / / [1, 2, 3]
console.log(new Array({a: 1.b: 2})) // [{a: 1, b: 2}]
console.log(new Array([1.2.3])) / / [[1, 2, 3]]
Copy the code

Array.from

An Array of classes (containing the Length attribute) or an iterable (implementing the @@iterator iterable protocol) creates a new, shallow-copied Array instance.

The first argument to array. from takes an array-like object or an object that implements an iterable protocol, the second argument takes a function that processes the value of each item during iteration, and the third argument is the execution context of the second function, this object

console.log(Array.from(1)) / / []
console.log(Array.from(null)) // TypeError NULL does not implement the iterable protocol
console.log(Array.from(undefined)) // TypeError undefined does not implement the iterable protocol
console.log(Array.from(1.2.3)) // TypeError The second argument is not a function
console.log(Array.from({0: 1.1: 2.length: 2})) // [{a: 1, b: 2}]
console.log(Array.from([1.2.3])) // [1, 2, 3] arrays implement the iterable protocol
console.log(Array.from([1[2].3])) / / [1, [2], 3]

Copy the code

Commonly used for function arguments and DOM node method class array conversion