今日分享:
每一步都是曼妙的风景~
_.drop(array, [n=1])
使用:
创建一个切片数组,去除array前面的n个元素。(n默认值为1。)
使用示例:
_.drop([1, 2, 3]);
// => [2, 3]
_.drop([1, 2, 3], 2);
// => [3]
_.drop([1, 2, 3], 5);
// => []
_.drop([1, 2, 3], 0);
// => [1, 2, 3]
尝试手写:
①返回新数组;②按n 切除;③n为空时默认切除第一个
let drop_arr = [1,2,3,4,5];
function my_drop(arr, n=1){
if(n > 0 && n < arr.length) {
let newArr = Array(arr.length - n);
for(var i = n; i < arr.length; i++){
newArr[i-n] = arr[i]
}
return newArr;
}
}
console.log(my_drop(drop_arr,2)); // [3,4,5]
源码方案:
function drop(array, n, guard) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
return baseSlice(array, n < 0 ? 0 : n, length);
}
// 核心源码
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
// 判断n值有效
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = end > length ? length : end;
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
备注
一开始用slice或者其他数组方法写的,然后反应过来我在用一个基础方法替换另一个基础方法,后来换成for循环和index这种纯原生写。新增一个数组然后用循环迭代的方法替换空值。
lodash很大的优势是 入参有问题、存在空值等类似会报错的情况都能处理,不会直接阻塞代码运行。看他的源码也能看出来,对各种错误情况的处理占用了大量篇幅。
相关方法
_.dropRight(array, [n=1])
创建一个切片数组,去除array尾部的n个元素。(n默认值为1。)
使用示例:
_.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]
__.dropRightWhile(array, [predicate=_.identity])
创建一个切片数组,去除array中从 predicate 返回假值开始到尾部的部分。predicate 会传入3个参数: (value, index, array)。
使用示例:
var users = [
{ 'user': 'barney', 'active': true },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': false }
];
_.dropRightWhile(users, function(o) { return !o.active; });
// => objects for ['barney']
// The `_.matches` iteratee shorthand.
_.dropRightWhile(users, { 'user': 'pebbles', 'active': false });
// => objects for ['barney', 'fred']
// The `_.matchesProperty` iteratee shorthand.
_.dropRightWhile(users, ['active', false]);
// => objects for ['barney']
// The `_.property` iteratee shorthand.
_.dropRightWhile(users, 'active');
// => objects for ['barney', 'fred', 'pebbles']
__.dropWhile(array, [predicate=_.identity])
创建一个切片数组,去除array中从起点开始到 predicate 返回假值结束部分。predicate 会传入3个参数: (value, index, array)。
使用示例
var users = [
{ 'user': 'barney', 'active': false },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': true }
];
_.dropWhile(users, function(o) { return !o.active; });
// => objects for ['pebbles']
// The `_.matches` iteratee shorthand.
_.dropWhile(users, { 'user': 'barney', 'active': false });
// => objects for ['fred', 'pebbles']
// The `_.matchesProperty` iteratee shorthand.
_.dropWhile(users, ['active', false]);
// => objects for ['pebbles']
// The `_.property` iteratee shorthand.
_.dropWhile(users, 'active');
// => objects for ['barney', 'fred', 'pebbles']