主题
Lodash
介绍
Lodash 是 JavaScript 实用工具库。
函数
debounce
语法:
_.debounce(func, [wait=0], [options=])
func (Function): 要防抖动的函数。[wait=0] (number): 需要延迟的毫秒数。[options=] (Object): 选项对象。[options.leading=false] (boolean): 指定在延迟开始前调用。[options.maxWait] (number): 设置 func 允许被延迟的最大值。[options.trailing=true] (boolean): 指定在延迟结束后调用。
示例:
js
// 避免窗口在变动时出现昂贵的计算开销。
jQuery(window).on('resize', _.debounce(calculateLayout, 150))
// 当点击时 `sendMail` 随后就被调用。
jQuery(element).on(
'click',
_.debounce(sendMail, 300, {
leading: true,
trailing: false,
}),
)
// 确保 `batchLog` 调用1次之后,1秒内会被触发。
var debounced = _.debounce(batchLog, 250, { maxWait: 1000 })
var source = new EventSource('/stream')
jQuery(source).on('message', debounced)
// 取消一个 trailing 的防抖动调用
jQuery(window).on('popstate', debounced.cancel)throttle
语法:
_.throttle(func, [wait=0], [options=])
func (Function): 要节流的函数。[wait=0] (number): 需要节流的毫秒。[options=] (Object): 选项对象。[options.leading=true] (boolean): 指定调用在节流开始前。[options.trailing=true] (boolean): 指定调用在节流结束后。
示例:
js
// 避免在滚动时过分的更新定位
jQuery(window).on('scroll', _.throttle(updatePosition, 100))
// 点击后就调用 `renewToken`,但5分钟内超过1次。
var throttled = _.throttle(renewToken, 300000, { trailing: false })
jQuery(element).on('click', throttled)
// 取消一个 trailing 的节流调用。
jQuery(window).on('popstate', throttled.cancel)对象
pick
语法:
_.pick(object, [props])
示例:
js
var object = { a: 1, b: '2', c: 3 }
_.pick(object, ['a', 'c'])
// => { 'a': 1, 'c': 3 }omit
语法:
_.omit(object, [props])
示例:
js
var object = { a: 1, b: '2', c: 3 }
_.omit(object, ['a', 'c'])
// => { 'b': '2' }