3.3 last
3.3.1语法
_.last(array, [n]);
3.3.2说明
last接收2个参数。第一个参数array,第二个参数为选填,有隐藏的第三个属性;
默认返回array(数组)的最后一个元素。非数组
传递 n参数将返回数组中从最后n个元素(注:从1开始计数,并非从0)。
返回的是一个数组。
3.3.3示例
示例一:基本用法,
var array = [1, 2, 3, 4],
result;
// 返回最后一个元素
result = _.last(array);
console.log(result); //=> 4
// 返回最后一个元素的另一种写法
result = _(array).last();
console.log(result); //=> 4
// 使用原生方法返回最后一个元素
result = array.slice(-1)[0];
console.log(result); //=> 4
不传n的时候,返回的是数组最后一个元素。
示例二:传了第二个参数n
var array = [1, 2, 3, 4],
result;
// 返回一个元素组成的数组。
result = _.last(array, 1);
console.log(result); //=> [4]
// 返回后面两个元素,
result = _.last(array, 2);
console.log(result); //=> [3, 4]
// 当n大于数组长度时,整个数组
result = _.last(array, 10);
console.log(result); //=> [1, 2, 3, 4]
// 当参数n小于等于0,将返回一个空的数组
result = _.last(array, 0);
console.log(result); //=> []
当传入了n,返回后面n个元素组成的数组,n传1,返回的也是数组。
3.3.4 隐藏的第三个参数
// 传了true之后,只返回数组最后一个元素,n失效
var array = [1, 2, 3, 4],
result;
result = _.last(array, 2, true);
console.log(result); //=> 4
result = _.last(array, 2, false);
console.log(result); //=> [3, 4]
3.3.5 传递了特殊的参数
var result = _.last(null);
console.log(result); //=> undefined
3.3.6 配合_.map方法使用
var result = _.map([[1, 2, 3], [1, 2, 3, 4]], _.last);
console.log(result); //=> [3, 4]