lodash 基礎(chǔ)篇 slice函數(shù)

先看一下基本用法
_.slice(array, [start=0], [end=array.length])
裁剪數(shù)組array,從 start 位置開始到end結(jié)束,但不包括 end 本身的位置。

 var arrayList=[1,2,3,4,5,6,7];
 console.log(arrayList);
 console.log(_.slice(arrayList,null,3)); //[1,2,3]
 console.log(_.slice(arrayList,-3,-2)); //[5]
 console.log(_.slice(arrayList,-2));//[6,7]

我們先看一下lodash的代碼然后一行一行解讀

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
}

首先是數(shù)組array是否合法的判斷:先判斷數(shù)組是否是null,是null返回0,否則是數(shù)組的長度,js中0是false,!0是true,數(shù)組不存在直接返回。

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

開始位置start和結(jié)束位置end默認(rèn)值:start 不尋在的話取0,end不存在取數(shù)組的長度。

  start = start == null ? 0 : start
  end = end === undefined ? length : end

start和end支持負(fù)數(shù),如果start是負(fù)數(shù),假如是數(shù)組是[1,2,3,4,5],start是-2,當(dāng)-start就是2,2不大于5,start就等于3,end若大于數(shù)組長度,取數(shù)組的長度,若果end小于0,end就等于length+(end)。

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

在MDN中:>>>是無符號右移,>>是有符號移位
1 如果不能轉(zhuǎn)換為Number,那就為0
2 如果為非整數(shù),先轉(zhuǎn)換為整數(shù)
3 如果是正數(shù),返回正數(shù),如果是負(fù)數(shù),返回負(fù)數(shù) + 2的32次方

length = start > end ? 0 : ((end - start) >>> 0)
  start >>>= 0

接下來就是循環(huán)判斷最后把result返回

 let index = -1
  const result = new Array(length)
  while (++index < length) {
    result[index] = array[index + start]
  }
  return result
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容