npm模块学习之array-last
发布于 5 年前 作者 sunfeng90 2096 次浏览 来自 分享

1、git地址

https://github.com/jonschlinkert/array-last

2、作用

获取数组最后一个或者后几个元素

3、例子和源码解析

3.1 例子

const last = require('array-last');

console.log(last(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])) // 输出:h

console.log(last(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], 1)) // 输出:h

console.log(last(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], 3)) // 输出:[ 'f', 'g', 'h' ]

console.log(last(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], '3')) // 输出:[ 'f', 'g', 'h' ]

console.log(last(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], undefined)) // 输出:h

console.log(last(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], null)) // 输出:h

console.log(last(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], '')) // 输出:h

3.2 源码

var isNumber = require('is-number');

module.exports = function last(arr, n) {
  if (!Array.isArray(arr)) {
    throw new Error('expected the first argument to be an array');
  }

  var len = arr.length;
  if (len === 0) {
    return null;
  }

  n = isNumber(n) ? +n : 1;
  if (n === 1) {
    return arr[len - 1];
  }

  var res = new Array(n);
  while (n--) {
    res[n] = arr[--len];
  }
  return res;
};

3.3 源码解析

1)该模块一共两个参数,第一个参数是数组,第二个是或者数据的个数;

2)如果第一个参数传入的不是数组,会暴露类型错误异常;

3)接着获取数组的长度,如果传入的是空数组,那么就返回null;

4)接着判断传入的个数n是否为数字类型。如果不是,n默认为1;

5)如果n为1,那么获取数组最后一个元素,并返回;

6)然后定义一个新数组res。接着在while循环中获取数组n个数据,并保存到res;

7)最后返回res。

回到顶部