发布于 2016-01-10 21:47:31 | 184 次阅读 | 评论: 0 | 来源: PHPERZ

这里有新鲜出炉的精品教程,程序狗速度看过来!

lodash JavaScript 实用工具库

lodash 是一个 JavaScript 实用工具库,提供一致性,模块化,性能和配件等功能。


Lodash 中文文档 (v3.10.1) - “Function” 方法

Translated by PeckZeg
Original Docs: Lodash v3.10.1 Docs

说明

部分方法参考 @愚人码头 的关于 Underscore 的翻译

“Function” 方法

_.after(n, func)

作用与 _.before 相反,该方法创建一个在 func 被调用 n (或更多)次后才执行的函数。

参数

  1. n (number) : 执行前 func 被调用的次数

  2. func (Function) : 待约束的函数

返回

(Function) : 返回一个已约束的函数Returns the new restricted function.

示例

var saves = ['profile', 'settings'];

var done = _.after(saves.length, function() {
  console.log('done saving!');
});

_.forEach(saves, function(type) {
  asyncSave({ 'type': type, 'complete': done });
});
// → 在两次异步保存完成之后记录 'done saving!'

_.ary(func, [n=func.length])

Creates a function that accepts up to n arguments ignoring any additional arguments.

创建一个接受至少多n 个参数并忽略掉其他额外参数的函数。

参数

  1. func (Function) : 待覆盖参数的函数

  2. [n=func.length] (number) : 覆盖的数量

返回

(Function) : 返回新函数

示例

_.map(['6', '8', '10'], _.ary(parseInt, 1));
// → [6, 8, 10]

_.before(n, func)

Creates a function that invokes func, with the this binding and arguments of the created function, while it’s called less than n times. Subsequent calls to the created function return the result of the last func invocation.

创建一个能够执行 func 的函数,该包装函数能够正常绑定 this 和参数,该函数只能够被调用少于 n 次,之后的调用将返回最后一次调用的结果。

参数

  1. n (number) : 函数在调用失效之前能够执行的次数

  2. func (Function) : 待约束的函数

返回

(Function) : 返回一个已约束的新函数

示例

jQuery('#add').on('click', _.before(5, addContactToList));
// → 允许添加至多 4 个联系人到列表

_.bind(func, thisArg, [partials])

创建一个引用于 func 并将 thisArg 绑定至 this 的函数,额外传入 _.bind 的参数将作为 func 的参数传入。

_.bind.placeholder 的值,在整体构建中的默认值是 _,可以作为部分参数的占位符传入。

注意:不像源生的 Function#bind,该方法不能为绑定的函数设置 length 属性

参数

  1. func (Function) : 待绑定的函数

  2. thisArg (*) : func 绑定的 this

  3. [partials] (…*) : 部分应用的参数

返回

(Function) : 返回一个已绑定的新函数

示例

var greet = function(greeting, punctuation) {
  return greeting + ' ' + this.user + punctuation;
};

var object = { 'user': 'fred' };

var bound = _.bind(greet, object, 'hi');
bound('!');
// → 'hi fred!'

// 使用占位符
var bound = _.bind(greet, object, _, '!');
bound('hi');
// → 'hi fred!'

_.bindAll(object, [methodNames])

为一个对象的方法绑定对象本身(会覆盖已存在的方法)。方法名可以指定为单独的参数,也可指定为一个方法名数组。如果没有指定方法名,则会查找对象所有的可枚举的、自有和内置函数属性。

注意:该方法不能为绑定的函数设置 length 属性。

参数

  1. object (Object) : 待绑定(选择绑定方法)的对象

  2. [methodNames] (…(string|string[]) : 待绑定的对象方法名,可指定为单独的参数,也可指定为一个方法名数组

参数

(Object) : 返回对象

示例

var view = {
  'label': 'docs',
  'onClick': function() {
    console.log('clicked ' + this.label);
  }
};

_.bindAll(view);
jQuery('#docs').on('click', view.onClick);
// → 当元素被单击时记录 'clicked docs'

_.bindKey(object, key, [partials])

Creates a function that invokes the method at object[key] and prepends any additional _.bindKey arguments to those provided to the bound function.

创建一个能够执行位于 object[key] 方法的函数,执行时会将额外传入 _.bindKey 的参数传入绑定的函数。

This method differs from _.bind by allowing bound functions to reference methods that may be redefined or don’t yet exist. See Peter Michaux’s article for more details.

该方法不同于 _.bind,其允许绑定的函数重新引用一个可能还不存在的方法,查看 Peter Michaux 的文章 获得更多的信息。

_.bind.placeholder 的值,在整体构建中的默认值是 _,可以作为部分参数的占位符传入。

参数

  1. object (Object) : 方法所属的对象

  2. key (string) : 方法的键

  3. [partials] (…*) : 部分应用的参数

返回

(Function) : 返回一个已绑定的新函数

示例

var object = {
  'user': 'fred',
  'greet': function(greeting, punctuation) {
    return greeting + ' ' + this.user + punctuation;
  }
};

var bound = _.bindKey(object, 'greet', 'hi');
bound('!');
// → 'hi fred!'

object.greet = function(greeting, punctuation) {
  return greeting + 'ya ' + this.user + punctuation;
};

bound('!');
// → 'hiya fred!'

// 使用占位符
var bound = _.bindKey(object, 'greet', _, '!');
bound('hi');
// → 'hiya fred!'

_.curry(func, [arity=func.length])

创建一个能够接受 func 的一个或多个参数的函数。如果已提供所有 func 的参数,在调用时会执行 func 并返回其结果。否则则返回一个能够接收一个或多个 func 剩余的参数的函数,以此类推,在 func.length 不能使用时,需要手动指定 func 参数的个数。

_.curry.placeholder 的值,在整体构建中的默认值是 _,可以作为部分参数的占位符传入。

注意:该方法不能够设置科里化后的函数的 length 属性。

参数

  1. func (Function) : 待科里化的函数

  2. [arity=func.length] (number) : 函数的数量

返回

(Function) : 返回科里化的新函数

示例

var abc = function(a, b, c) {
  return [a, b, c];
};

var curried = _.curry(abc);

curried(1)(2)(3);
// → [1, 2, 3]

curried(1, 2)(3);
// → [1, 2, 3]

curried(1, 2, 3);
// → [1, 2, 3]

// 使用占位符
curried(1)(_, 3)(2);
// → [1, 2, 3]

_.curryRight(func, [arity=func.length])

该方法类似 _.curry 但其添加的行为由 _.partial 变更为 _.partialRight

_.curryRight.placeholder 的值,在整体构建中的默认值是 _,可以作为部分参数的占位符传入。

注意:该方法不能够设置科里化后的函数的 length 属性

参数

  1. func (Function) : 待科里化的函数

  2. [arity=func.length] (number) : 函数的数量

返回

(Function) : 返回科里化的新函数

示例

var abc = function(a, b, c) {
  return [a, b, c];
};

var curried = _.curryRight(abc);

curried(3)(2)(1);
// → [1, 2, 3]

curried(2, 3)(1);
// → [1, 2, 3]

curried(1, 2, 3);
// → [1, 2, 3]

// 使用占位符
curried(3)(1, _)(2);
// → [1, 2, 3]

_.debounce(func, [wait=0], [options])

创建一个防反跳的函数,其将 func 的执行延迟到最后一次防反跳函数执行后的 wait 毫秒之后。防反跳函数拥有一个 cancel 方法可以取消延迟调用。其还提供一个选项对象,以待在 func 在调用超时前/后的临界点时被调用。

注意:如果防反跳函数在等待超时的过程中已被执行且 leadingtrailing 均指定为 true,那么 func 将仅在调用超时临界点后被执行。

查看 David Corbacho 的文章 以获取 _.debounce_.throttle 之间区别的细节。

参数

  1. func (Function) : 待绑定防反跳特性的函数

  2. [wait=0] (number) : 待延迟的毫秒数

  3. [options] _(Object)_: 选项对象

  4. [options.leading=false] _(boolean)_: 指定是否在超时临界点前执行

  5. [options.maxWait] (number) : 在执行前允许的 func 最大延迟时间

  6. [options.trailing=true] (boolean) : 指定是否在超时临界点后执行

返回

(Function) : 返回一个防反跳的新函数

示例

//    避免在窗口尺寸不断变化的时候进行大量计算
jQuery(window).on('resize', _.debounce(calculateLayout, 150));

//    当点击点击触发时,执行 `sendMail` 时防反跳
jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
  'leading': true,
  'trailing': false
}));

//    允许 `batchLog` 执行时允许 1 秒的防反跳调用
var source = new EventSource('/stream');
jQuery(source).on('message', _.debounce(batchLog, 250, {
  'maxWait': 1000
}));

//    取消一个防反跳调用
var todoChanges = _.debounce(batchLog, 1000);
Object.observe(models.todo, todoChanges);

Object.observe(models, function(changes) {
  if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
    todoChanges.cancel();
  }
}, ['delete']);

//    ...在某时刻 `models.todo` 已经发生变化
models.todo.completed = true;

//    ...在 1 秒前已经删除了 `models.toto`
//    其已经取消了防反跳的 `todoChanges` 调用
delete models.todo;

_.defer(func, [args])

推迟执行 func 直到当前调用栈被清空。此外,在执行时额外的参数将会传入 func

参数

  1. func (Function) : 待推迟执行的函数

  2. [args] (…*) : ·执行函数时伴随的参数

返回

(number) : 返回定时器的编号。

示例

_.defer(function(text) {
  console.log(text);
}, 'deferred');
// 在延迟一毫秒或更多毫秒之后记录 'deferred'

_.delay(func, wait, [args])

Invokes func after wait milliseconds. Any additional arguments are provided to func when it’s invoked.

wait 毫秒之后执行 func。在执行时任何外的参数将会传入 func

参数

  1. func (Function) : 待延迟的函数

  2. wait (number) : 延迟执行的毫秒数

  3. [args] (…*) : 函数执行时伴随的参数

返回

(number) : 返回定时器的编号

示例

_.delay(function(text) {
  console.log(text);
}, 1000, 'later');
// → 在 1 秒后记录 'later'

_.flow([funcs])

创建一个能够返回执行指定函数(为创建的函数绑定 this 指针)后的结果的函数,在执行时每次成功的调用将会把返回的值传递给下一个函数。

参数

  1. [funcs] (…Function) : 待执行的函数组

返回

(Function) : 返回一个新函数

示例

function square(n) {
  return n * n;
}

var addSquare = _.flow(_.add, square);
addSquare(1, 2);
// → 9

_.flowRight([funcs])

该方法类似 _.flow,但其创建一个从右往左开始执行函数组的函数。

别名

  • _.backflow

  • _.compose

参数

  1. [funcs] (…Function) : 待执行的函数组

返回

(Function) : 返回一个新函数

示例

function square(n) {
  return n * n;
}

var addSquare = _.flowRight(square, _.add);
addSquare(1, 2);
// → 9

_.memoize(func, [resolver])

创建一个可以缓存 func 的执行结果的函数。如果提供了 resolver,那么其决定缓存结果的键将基于缓存器函数提供的参数。默认情况下,第一个参数将被指定的缓存器函数,将被强制转换成字符串以作为缓存键使用。func 在执行时绑定的 this 将是缓存器函数。

注意:缓存器函数的缓存需要暴露缓存属性,其产物会覆盖 _.memoize.CacheCache 构造器将拥有一个其实例并继承 Map,并拥有 get, hasset 接口。

参数

  1. func (Function) : 拥有其输出缓存器的函数

  2. [resolver] (Function) : 解决缓存键的函数

返回

(Function) : 返回一个新的缓存器函数

示例

var upperCase = _.memoize(function(string) {
  return string.toUpperCase();
});

upperCase('fred');
// → 'FRED'

// 修改结果缓存
upperCase.cache.set('fred', 'BARNEY');
upperCase('fred');
// → 'BARNEY'

// 替换 `_.memoize.Cache`
var object = { 'user': 'fred' };
var other = { 'user': 'barney' };
var identity = _.memoize(_.identity);

identity(object);
// → { 'user': 'fred' }
identity(other);
// → { 'user': 'fred' }

_.memoize.Cache = WeakMap;
var identity = _.memoize(_.identity);

identity(object);
// → { 'user': 'fred' }
identity(other);
// → { 'user': 'barney' }

_.modArgs(func, [transforms])

Creates a function that runs each argument through a corresponding transform function.

创建一个对各个参数运行对应的变换函数的函数。

参数

  1. func (Function) : 待包裹的函数

  2. [transforms] (…(Function|Function[]) : 变换参数的函数,可以指定为单个参数,也可以指定为函数数组

返回

(Function) : 返回新函数

示例

function doubled(n) {
  return n * 2;
}

function square(n) {
  return n * n;
}

var modded = _.modArgs(function(x, y) {
  return [x, y];
}, square, doubled);

modded(1, 2);
// → [1, 4]

modded(5, 10);
// → [25, 20]

_.negate(predicate)

创建一个执行结果与断言函数 func 相反的函数。func 断言函数在执行时会绑定 this 并传入创建函数的参数。

参数

  1. predicate (Function) : 待否定的断言函数

返回

(Function) : 返回一个新的函数

示例

function isEven(n) {
  return n % 2 == 0;
}

_.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
// → [1, 3, 5]

_.once(func)

创建一个只执行一次 func 的函数。重复调用函数将返回首次调用的值。func 在执行时将绑定 this 并传入创建函数的参数。

参数

  1. func (Function) : 待限制的函数

返回

(Function) : 返回已限制的新函数

示例

var initialize = _.once(createApplication);
initialize();
initialize();
// `initialize` invokes `createApplication` once

_.partial(func, [partials])

创建一个能够执行在 func 时预先填入部分 partial 参数的函数。该方法类似于 _.bind,但其无法变更 this 绑定。

_.partial.placeholder 的值,在整体构建中的默认值是 _,可以作为部分参数的占位符传入。

注意:该方法不能给添加了部分参数的函数设置 length 属性。

参数

  1. func (Function) : 待添加部分参数的函数

  2. [partials] (…*) : 待添加的部分参数

返回

(Function) : 返回一个已添加部分参数的函数

示例

var greet = function(greeting, name) {
  return greeting + ' ' + name;
};

var sayHelloTo = _.partial(greet, 'hello');
sayHelloTo('fred');
// → 'hello fred'

// 使用占位符
var greetFred = _.partial(greet, _, 'fred');
greetFred('hi');
// → 'hi fred'

_.partialRight(func, [partials])

该方法类似于 _.partial,但其绑定参数的顺序是从右往左的。

_.partialRight.placeholder 的值,在整体构建中的默认值是 _,可以作为部分参数的占位符传入。

注意:该方法不能给添加了部分参数的函数设置 length 属性。

参数

  1. func (Function) : 待添加部分参数的函数

  2. [partials] (…*) : 待添加的部分参数

返回

(Function) : 返回一个已添加部分参数的函数

示例

var greet = function(greeting, name) {
  return greeting + ' ' + name;
};

var greetFred = _.partialRight(greet, 'fred');
greetFred('hi');
// → 'hi fred'

// 使用占位符
var sayHelloTo = _.partialRight(greet, 'hello', _);
sayHelloTo('fred');
// → 'hello fred'

_.rearg(func, indexes)

创建一个执行 func 时能够指定传入参数的位置的函数,即如果指定首个索引的参数为首个参数,指定的第二个索引的参数将为第二个参数,以此类推。

参数

  1. func (Function) : 待重排参数的函数

  2. indexes (…(number|number[]) : 重排参数的索引,可以指定为单个参数也可以指定为索引数组

返回

(Function) : 返回一个新函数

示例

var rearged = _.rearg(function(a, b, c) {
  return [a, b, c];
}, 2, 0, 1);

rearged('b', 'c', 'a')
// → ['a', 'b', 'c']

var map = _.rearg(_.map, [1, 0]);
map(function(n) {
  return n * 3;
}, [1, 2, 3]);
// → [3, 6, 9]

_.restParam(func, [start=func.length-1])

创建一个函数,其在执行时会绑定创建的函数的 this 绑定,并会传入从 start 开始的参数指定为一个数组。

注意:该方法基于 rest parameter

参数

  1. func (Function) : 待添加剩余参数的函数

  2. [start=func.length-1] (number) : 剩余参数的开始位置

返回

(Function) : 返回一个新函数

示例

var say = _.restParam(function(what, names) {
  return what + ' ' + _.initial(names).join(', ') +
    (_.size(names) > 1 ? ', & ' : '') + _.last(names);
});

say('hello', 'fred', 'barney', 'pebbles');
// → 'hello fred, barney, & pebbles'

_.spread(func)

创建一个函数,其在执行 func 时会绑定创建的函数的 this 绑定,并传入一个类似于 Function#apply 的数组参数。

注意:该函数基于 spread operator

参数

  1. func (Function) : 待展开参数的函数

返回

(Function) : 返回新的函数

示例

var say = _.spread(function(who, what) {
  return who + ' says ' + what;
});

say(['fred', 'hello']);
// → 'fred says hello'

// with a Promise
var numbers = Promise.all([
  Promise.resolve(40),
  Promise.resolve(36)
]);

numbers.then(_.spread(function(x, y) {
  return x + y;
}));
// → a Promise of 76

_.throttle(func, [wait=0], [options])

创建一个节流阀函数,其将 func 的执行延迟到最后一次节流阀函数执行后的 wait 毫秒之后。节流阀函数拥有一个 cancel 方法可以取消延迟调用。其还提供一个选项对象,以待在 func 在调用超时前/后的临界点时被调用。

注意:如果节流阀函数在等待超时的过程中已被执行且 leadingtrailing 均指定为 true,那么 func 将仅在调用超时临界点后被执行。

查看 David Corbacho 的文章 以获取 _.debounce_.throttle 之间区别的细节。

参数

  1. func (Function) : 待绑定节流阀特性的函数

  2. [wait=0] (number) : 待延迟的毫秒数

  3. [options] _(Object)_: 选项对象

  4. [options.leading=false] _(boolean)_: 指定是否在超时临界点前执行

  5. [options.maxWait] (number) : 在执行前允许的 func 最大延迟时间

  6. [options.trailing=true] (boolean) : 指定是否在超时临界点后执行

返回

(Function) : 返回一个节流阀特性的新函数

示例

//    避免在滚动时过度更新位置
jQuery(window).on('scroll', _.throttle(updatePosition, 100));

//    当连续触发单击事件时,保证 5 秒内只会执行一次 `renewToken`
jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
  'trailing': false
}));

//    取消一个节流阀后的调用
jQuery(window).on('popstate', throttled.cancel);

_.wrap(value, wrapper)

创建一个函数,其将 value 作为第一个参数传递给包装函数。任何额外的参数将附加到包装函数之中。包装函数会绑定创建的函数的 this 绑定。

参数

  1. value (*) : 待包装的值

  2. wrapper (Function) : 包装函数

返回

(Function) : 返回新的函数

示例

var p = _.wrap(_.escape, function(func, text) {
  return '<p>' + func(text) + '<p>';
});

p('fred, barney, & pebbles');
// → '<p>fred, barney, &amp; pebbles<p>'


最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务