Skip to content

初探lodash #1

Description

@youngwind

目录

  1. array
  2. chain

Array

1.1 _.chunk(array, [size=1])平均分配数组到一个新的数组中

console.log(_.chunk(['a', 'b', 'c', 'd', 'e'], 1));
console.log(_.chunk(['a', 'b', 'c', 'd', 'e'], 2));
console.log(_.chunk(['a', 'b', 'c', 'd', 'e'], 3));
console.log(_.chunk(['a', 'b', 'c', 'd', 'e'], 4));
============================
[ [ 'a' ], [ 'b' ], [ 'c' ], [ 'd' ], [ 'e' ] ]
[ [ 'a', 'b' ], [ 'c', 'd' ], [ 'e' ] ]
[ [ 'a', 'b', 'c' ], [ 'd', 'e' ] ]
[ [ 'a', 'b', 'c', 'd' ], [ 'e' ] ]

1.2 _.compact(array) 数组去除null、0、false、“”、undefined、NaN项

console.log(_.compact([0,1,'',2,NaN,false,undefined,null,'3']))
=================================
[ 1, 2, '3' ]

1.3. _.difference(array,[values]) 差异对比,返回array中不存在[values]中的值

console.log(_.difference([1,2,3,4,5,6],[4,2]));
console.log(_.difference([1,2,3,4,5,6],[4,6,7]));
console.log(_.difference([1,2,3,4,5,6],[1,2,3]));
=============================================
[ 1, 3, 5, 6 ]
[ 1, 2, 3, 5 ]
[ 4, 5, 6 ]

1.4. _.drop(array,[n=1]) 从数组头删除n个元素,相当于unshift方法

_.drop([1,2,3])     => [2,3]
_.drop([1,2,3],2)  => [3]
_.drop([1,2,3],5)  => []

1.5 _.dropRight(array,[n=1]) 从数组尾删除n个元素,相当于pop方法

_.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]

1.6 _.dropRightWhile
1.7 _.ropWhile

1.8 _.fill(array, value, [start=0], [end=array.length]) 从array[start]到array[end]替换为value,不包括array[end]

var array = [1, 2, 3];

_.fill(array, 'a');
console.log(array);
// → ['a', 'a', 'a']

_.fill(Array(3), 2);
// → [2, 2, 2]

_.fill([4, 6, 8], '*', 1, 2);
// → [4, '*', 8]

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions