lodash 数组转换函数castArray

castArray的作用是把传入的第一个实参通过数组字面量的方式转换为数组,如果已经是一个数组,则直接返回它。源码非常简单,如下:

function castArray(...args) {
  // 参数未传返回一个空数组
  if (!args.length) {
    return []
  }
  // 获取第一个参数
  const value = args[0]
  // 如果已经是数组则返回它自身,如果不是则用数组字面量的形式包裹返回
  return Array.isArray(value) ? value : [value]
}
复制代码

Array.of

Array.of() 方法从可变数量的参数创建一个新的 Array 实例,而不管参数的数量或类型如何。

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]]
复制代码

上述结果可以看出:

  • castArray函数不支持多个参数转换为数组
  • 对于本身就是数组的参数,castArray函数会直接返回该数组

new Array

console.log(new Array(1)) // [ <1 empty item> ] 传入一个数字参数,创建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]]
复制代码

Array.from

类数组(包含length属性)或可迭代对象(实现了@@iterator可迭代协议)创建一个新的、浅复制的 Array 实例。

Array.from的第一个参数接收一个类数组对象或实现了可迭代协议的对象,第二个参数接收一个函数,用于在迭代过程中处理每一项的值,第三个参数是第二个函数的执行上下文this对象

console.log(Array.from(1)) // []
console.log(Array.from(null)) // TypeError null没有实现了可迭代协议
console.log(Array.from(undefined)) // TypeError undefined没有实现了可迭代协议
console.log(Array.from(1, 2, 3)) // TypeError 第二个参数不是函数
console.log(Array.from({0: 1, 1: 2, length: 2})) // [{a: 1, b: 2}]
console.log(Array.from([1, 2, 3])) // [1, 2, 3] 数组实现了可迭代协议
console.log(Array.from([1, [2], 3])) // [1, [2], 3]

复制代码

常用于函数argumentsDOM节点方法类数组的转换

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享