_.initial(array)
20
_.initial(array)
_.initial方法获取一个数组的所有元素去除最后一个元素的切片
参数
array (Array): 需要查询的数组
返回值
(Array): 返回数组的切片
例子
_.initial([1, 2, 3]); // => [1, 2]
源代码:
import slice from './slice.js' /** * Gets all but the last element of `array`. * * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * initial([1, 2, 3]) * // => [1, 2] */ //获取一个数组的所有元素去除最后一个元素的切片 function initial(array) { const length = array == null ? 0 : array.length//数组长度 return length ? slice(array, 0, -1) : []//如果长度为0,返回空数组,否则调用slice获取切片 } export default initial
下面是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