每天学习几个node库 o(^▽^)┛
————————————————————

array-first github链接: https://github.com/jonschlinkert/array-first

这个库提供了获取一个数组前几位的序列的方法,原理是基于javascript对数组的原生方法slice,默认获取数组第一项并返回

tips:

方法中使用了 + 对变量进行隐式转换成整形变量

代码如下:

jonschlinkertlink
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/*!
* array-first <https://github.com/jonschlinkert/array-first>
*
* Copyright (c) 2014 Jon Schlinkert, contributors.
* Licensed under the MIT license.
*/

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

module.exports = function arrayFirst(arr, num) {
if (!Array.isArray(arr)) {
throw new Error('array-first expects an array as the first argument.');
}

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

var first = slice(arr, 0, isNumber(num) ? +num : 1);
if (+num === 1 || num == null) {
return first[0];
}
return first;
};

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

这个库提供了获取一个数组最后几项的方法,原理是先判断截取数组的长度,如为1,则返回数组序列为数组长度-1的项,否则,降序遍历截取长度作为数组的序列获取被截取数组,返回出最终结果,默认获取数组最后一项并返回

jonschlinkertlink
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*!
* array-last <https://github.com/jonschlinkert/array-last>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/

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;
};