Lodash源碼分析-castArray.js

前言

此方法沒有對其餘方法進行引用數組

正文

源代碼

/**
  * Casts `value` as an array if it's not one.
  *
  * @since 4.4.0
  * @category Lang
  * @param {*} value The value to inspect.
  * @returns {Array} Returns the cast array.
  * @example
  *
  * castArray(1)
  * // => [1]
  *
  * castArray({ 'a': 1 })
  * // => [{ 'a': 1 }]
  *
  * castArray('abc')
  * // => ['abc']
  *
  * castArray(null)
  * // => [null]
  *
  * castArray(undefined)
  * // => [undefined]
  *
  * castArray()
  * // => []
  *
  * const array = [1, 2, 3]
  * console.log(castArray(array) === array)
  * // => true
  */
function castArray(...args) {
  if (!args.length) {
    return []
  }
  const value = args[0]
  return Array.isArray(value) ? value : [value]
}

export default castArray
複製代碼

解析

參數

該方法接受任何形式的參數源碼分析

返回值

該方法返回一個數組post

方法解析

該方法首先會判斷傳入參數的個數,若無任何傳入參數,會直接返回給調用該方法的地方一個空數組,不然進行下一步。spa

下一步該方法會將傳入的第一個參數賦值給方法內聲明的value變量,而後判斷變量內的值(也就是傳入該方法的第一個參數)是否爲Array類型(即數組類型),若該值爲數組類型,則直接將其返回給調用該方法的地方,不然建立一個新數組將其做爲新數組第一項,並將該新數組返回給調用該方法的地方。code

注: 該方法無論傳入多少個參數,只會取傳入的第一個參數。get

示例

castArray(1)
--> [1]
castArray("1")
--> ["1"]
castArray({a: 1})
--> [(a: 1)]
castArray([1,2,3])
--> [1, 2, 3]
castArray(undefined)
--> [undefined]
castArray(null)
--> [null]
castArray(NaN)
--> [NaN]
castArray(Symbol("1"))
--> [Symbol(1)]
castArray(1,2)
--> [1]
複製代碼

相關連接:

每日源碼分析 - lodash(after.js)源碼

每日源碼分析 - lodash(chunk.js)it

本文章來源於午安煎餅計劃Web組 - 殘陽io

相關文章
相關標籤/搜索