_.dropRight(array, [n=1])
8
_.dropRight(array, [n=1])
类似于_.drop方法,_.dropRight方法创建数组的切片,从数组结尾位置丢弃n个元素,n默认为1
参数
array (Array): 需要创建切片的数组
[n=1] (number): 从结束位置开始丢弃的元素个数
返回值
(Array):返回一个新数组切片
例子
_.dropRight([1, 2, 3]); // => [1, 2] _.dropRight([1, 2, 3], 2); // => [1] _.dropRight([1, 2, 3], 5); // => [] _.dropRight([1, 2, 3], 0); // => [1, 2, 3]
源代码:
import slice from './slice.js' /** * Creates a slice of `array` with `n` elements dropped from the end. * * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @returns {Array} Returns the slice of `array`. * @example * * dropRight([1, 2, 3]) * // => [1, 2] * * dropRight([1, 2, 3], 2) * // => [1] * * dropRight([1, 2, 3], 5) * // => [] * * dropRight([1, 2, 3], 0) * // => [1, 2, 3] */ //类似于_.drop方法,创建数组的切片,从数组结尾位置丢弃n个元素,n默认为1 function dropRight(array, n=1) { const length = array == null ? 0 : array.length//数组长度 return length ? slice(array, 0, n < 0 ? 0 : -n) : [] //若数组长度为0,返回空数组,否则调用slice方法创建切片 //slice,一个参数是需要创建切片的数组,第二个参数是切片起始位置,第三个参数是切片结束位置 } export default dropRight
下面是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