五、lodash经常使用的函数

_.range(10) 生成0到9随机数
_.uniqueId() 生成不同的id,用于元素中的id值再好不过
_.clone 浅复制
_.cloneDeep(obj) 深拷贝

const option = cloneDeep(this.state.option); // immutable

_.groupBy

const sliceArr = groupBy(arr, x=>x[0].loop_index);
const sliceArr = groupBy(arr, Math.floor);

_.uniqWith 对象去重

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.uniqWith(objects, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]

_.isEqual 比较对象

var object = { 'a': 1 };
var other = { 'a': 1 };
_.isEqual(object, other); // => true
object === other;  // => false

_.pick 挑选对象

var object = { 'a': 1, 'b': '2', 'c': 3 };
 
_.pick(object, ['a', 'c']);
// => { 'a': 1, 'c': 3 }

基本连接词

  • by 根据方法或属性
  • with lodash方法比如isEqual
  • at 和index相关

array

  • chunk 分块
  • compact 去除假值元素
  • difference 和其他数组不同的值
  • flattendeep 全部拍平
  • frompairs 数组对转换成对象
  • intersection 交集
  • union 并集
  • xor 异或
  • pull 移除元素

集合

  • countBy 分类计数
  • groupBy 分组
  • orderBy
  • sortBy 排序
  • partition 多个判断
  • sample 采样
  • shuffle 打乱数组

function

  • debounce 连续时间内不触发
  • throttle 一段时间内会触发一次,用date实现
  • defer 推迟调用直到当前堆栈清理完毕
  • memoize 缓存
  • cloneDeep 深克隆
  • eq gt lt 等于 大于 小于
  • isEmpty
  • isNaN
  • toArray 对象或字符串转成数组

其他

  • mean 平均
  • sumBy
  • random
  • toPairs 对象转数组对

js自带数学方法

sort
字母排序用arr.sort((a,b)=>a-b) 没有用,所以需要如下比较函数,数字有用

arr.sort(function(a, b) {
    var nameA = a.nodeName.toUpperCase(); // ignore upper and lowercase
    var nameB = b.nodeName.toUpperCase(); // ignore upper and lowercase
    if (nameA < nameB) {
        return -1;
    }
    if (nameA > nameB) {
        return 1;
    }
    return 0;
});

你可能感兴趣的:(五、lodash经常使用的函数)