lodash和underscore:js实用工具库

一、对比

名称简介文档github最后提交star
lodashJavaScript 实用工具库docgithubGitHub last commit
underscore一个JavaScript实用库docgithubGitHub last commit

二、lodash

安装

npm i --save lodash

使用示例

var _ = require("lodash");

// 拆分数组
_.chunk(["a", "b", "c", "d"], 2);
// [ [ 'a', 'b' ], [ 'c', 'd' ] ]

// 过滤掉假值
console.log(_.compact([0, 1, false, 2, "", 3]));
// => [1, 2, 3]

// 打乱集合
console.log(_.shuffle([1, 2, 3]));
// [ 2, 3, 1 ]

// 查找数据
var users = [
  { id: 1, user: "barney" },
  { id: 2, user: "fred" },
  { id: 3, user: "pebbles" }
];

console.log(
  _.find(users, function(user) {
    return user.id == 1;
  })
);
// { id: 1, user: 'barney' }


// 浅拷贝
var objects = [{ a: 1 }, { b: 2 }];

var shallow = _.clone(objects);
console.log(shallow[0] === objects[0]);
// => true

// 深拷贝
var objects = [{ a: 1 }, { b: 2 }];

var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false

三、underscore

<script src="https://cdn.bootcdn.net/ajax/libs/underscore.js/1.13.0-0/underscore-umd.min.js"></script>

<button onclick="echo_debounce()">echo_debounce</button>

<button onclick="echo_throttle()">echo_throttle</button>

<script>
    // doc: https://underscorejs.net/#debounce
    // https://www.lodashjs.com/docs/lodash.debounce
    // 防抖:每次点击都会重新开始计时
    // _.debounce(function, wait, [immediate])
    function echo(){
        console.log('click');
    }

    const echo_debounce = _.debounce(echo, 3000)

    // 节流:点击后会锁定时间一段时间
    // _.throttle(function, wait, [options])
    const echo_throttle = _.throttle(echo, 3000)

</script>

参考
JS魔法堂:函数节流(throttle)与函数去抖(debounce)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值