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

本系列使用 lodash 4.17.4版本數組

1、源碼示例bash


/**
 * Creates a slice of `array` from `start` up to, but not including, `end`.
 *
 * **Note:** This method is used instead of
 * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are
 * returned.
 *
 * @since 3.0.0
 * @category Array
 * @param {Array} array The array to slice.
 * @param {number} [start=0] The start position.
 * @param {number} [end=array.length] The end position.
 * @returns {Array} Returns the slice of `array`.
 */
function slice(array, start, end) {
  let length = array == null ? 0 : array.length
  if (!length) {
    return []
  }
  start = start == null ? 0 : start
  end = end === undefined ? length : end

  if (start < 0) {
    start = -start > length ? 0 : (length + start)
  }
  end = end > length ? length : end
  if (end < 0) {
    end += length
  }
  length = start > end ? 0 : ((end - start) >>> 0)
  start >>>= 0

  let index = -1
  const result = new Array(length)
  while (++index < length) {
    result[index] = array[index + start]
  }
  return result
}

var ret = slice(['1','2','3','4'],1,3)

console.log(ret)
複製代碼

2、函數做用函數


上述示例代碼的結果是:源碼分析

[ '2', '3' ]
[Finished in 1.0s]
複製代碼

你們從結果能夠看出來,這個函數跟js裏封裝的slice函數是同樣的做用,slice(array, star, end),經過傳入一個數組,從數組中指定一個開始位置,一個結束位置做爲索引,深拷貝數組的一部分到新的數組,一般用來截取數組的子數組。post

3、函數工做原理ui


  1. 判斷參數合法性。

(1)判斷數組是否爲空:spa

let length = array == null ? 0 : array.length
if (!length) {
    return []
  }
複製代碼

(2)判斷參數start的合法性: * 判斷參數 start 是否爲空,若爲空,則取0; * 若是 start > 0,按正序取數組片斷,若 start < 0,則從右到左算起;code

start = start == null ? 0 : start
if (start < 0) {
    start = -start > length ? 0 : (length + start)
}
複製代碼

(3)判斷參數 end 的合法性: * 判斷參數 end 是否爲空,若爲空,則取length; * 判斷參數 end 是否超出數組長度,若超出,則取 length; * 若是 end > 0,按正序取數組片斷,若 end < 0,則從右到左算起;索引

end = end === undefined ? length : end
end = end > length ? length : end
if (end < 0) {
    end += length
}
複製代碼

(4)判斷參數 start 和 end 的邏輯合法性: * 若end 大於等於 start,則 length 取(end - start),即新數組長度;不然,length = 0,返回空數組; * 將參數 start 和 end 轉換爲十進制數;get

length = start > end ? 0 : ((end - start) >>> 0)
start >>>= 0
複製代碼
  1. 截取新數組,返回結果。

(1)建立一個新數組 result,長度爲length;

(2)讀取數組 array 中位置爲 start 到 end 的元素,存到新數組 result 中;

(3)返回新數組 result;

let index = -1
const result = new Array(length)
while (++index < length) {
    result[index] = array[index + start]
}
return result
複製代碼

本文章來源於午安煎餅計劃Web組 - 初見

相關連接:

每日源碼分析-Lodash(castArray.js)

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

每日源碼分析-Lodash(chunk.js

相關文章
相關標籤/搜索