_.take(array, [n=1])

45

_.take(array, [n=1])

_.take从数组开头取n个元素作为切片返回

参数

array (Array): 需要切片的数组
[n=1] (number): 切片有几个元素

返回值

(Array): 返回数组的切片

例子

_.take([1, 2, 3]);
// => [1]
 
_.take([1, 2, 3], 2);
// => [1, 2]
 
_.take([1, 2, 3], 5);
// => [1, 2, 3]
 
_.take([1, 2, 3], 0);
// => []

源代码:

import slice from './slice.js'

/**
 * Creates a slice of `array` with `n` elements taken from the beginning.
 *
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to query.
 * @param {number} [n=1] The number of elements to take.
 * @returns {Array} Returns the slice of `array`.
 * @example
 *
 * take([1, 2, 3])
 * // => [1]
 *
 * take([1, 2, 3], 2)
 * // => [1, 2]
 *
 * take([1, 2, 3], 5)
 * // => [1, 2, 3]
 *
 * take([1, 2, 3], 0)
 * // => []
 */
//从数组开头取n个元素作为切片返回
function take(array, n=1) {
  if (!(array != null && array.length)) {//如果数组为空或者为空数组,返回空数组
    return []
  }
  return slice(array, 0, n < 0 ? 0 : n)//调用slice方法获取从开头起的n个元素
}

export default take

slice

/**
 * 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. A negative index will be treated as an offset from the end.
 * @param {number} [end=array.length] The end position. A negative index will be treated as an offset from the end.
 * @returns {Array} Returns the slice of `array`.
 * @example
 *
 * var array = [1, 2, 3, 4]
 *
 * _.slice(array, 2)
 * // => [3, 4]
 */
//创建一个数组array的切片,从起始索引到结束索引,不包括结束索引
function slice(array, start, end) {//array要操作的数组,start起始索引,end结束索引
  let length = array == null ? 0 : array.length//数组长度
  if (!length) {//如果数组长度为0,就返回空数组
    return []
  }
  start = start == null ? 0 : start//start起始索引,默认值是0
  end = end === undefined ? length : end//end结束索引,默认是数组长度

  if (start < 0) {//起始索引是负数处理,是负数就相当于从末尾往开头数,也就是和lengh相加
    start = -start > length ? 0 : (length + start)//和length相加后如果还是小于0就等于0
  }
  end = end > length ? length : end//结束索引如果大于length就让它等于length
  if (end < 0) {//处理结束索引是负数
    end += length
  }
  length = start > end ? 0 : ((end - start) >>> 0)//根据start和end计算这个切片的长度,如果起始在结束后面那么切片长度为0,否则相减并且取整
  start >>>= 0//start取整

  let index = -1//循环索引
  const result = new Array(length)//创建切片长度的数组作为结果数组
  while (++index < length) {//循环切片长度的次数,给结果数组每一项赋值
    result[index] = array[index + start]
  }
  return result
}

export default slice

 

posted @ 2018-10-20 17:04  hahazexia  阅读(429)  评论(0)    收藏  举报