博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
下划线的学习7
阅读量:7195 次
发布时间:2019-06-29

本文共 7821 字,大约阅读时间需要 26 分钟。

Utility Functions

noConflict_.noConflict() 

Give control of the "_" variable back to its previous owner. Returns a reference to theUnderscore object.

var underscore = _.noConflict(); 解决_的冲突.

identity_.identity(value) 

Returns the same value that is used as the argument. In math: f(x) = x
This function looks useless, but is used throughout Underscore as a default iterator.

var moe = {name : 'moe'};moe === _.identity(moe);=> true 标识,看上去没用,但是_都用它作迭代,其实就是f(x) = x 不动点

times_.times(n, iterator, [context]) 

Invokes the given iterator function n times. Each invocation of iterator is called with anindex argument. 
Note: this example uses the .

_(3).times(function(n){ genie.grantWishNumber(n); }); 调用指定的iterator函数n次,每次都传递一个index参数,类似yield

random_.random(min, max) 

Returns a random integer between min and max, inclusive. If you only pass one argument, it will return a number between 0 and that number.

_.random(0, 100);=> 42 随机数

mixin_.mixin(object) 

Allows you to extend Underscore with your own utility functions. Pass a hash of {name: function} definitions to have your functions added to the Underscore object, as well as the OOP wrapper.

_.mixin({  capitalize : function(string) {    return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();  }});_("fabio").capitalize();=> "Fabio" 混入,通过它扩展_,通过{名称:函数}定义把函数加入_,作为OOP包装(这种包装模式很有意思,需要深入了解下)

uniqueId_.uniqueId([prefix]) 

Generate a globally-unique id for client-side models or DOM elements that need one. Ifprefix is passed, the id will be appended to it.

_.uniqueId('contact_');=> 'contact_104'

唯一标识,生成一个全局唯一的DOM标识.

escape_.escape(string) 

Escapes a string for insertion into HTML, replacing &<>"', and /characters.

_.escape('Curly, Larry & Moe');=> "Curly, Larry & Moe" 转义,消除HTML串的标记

unescape_.unescape(string) 

The opposite of , replaces &amp;&lt;&gt;&quot;&#x27;, and&#x2F; with their unescaped counterparts.

_.unescape('Curly, Larry & Moe');=> "Curly, Larry & Moe" 取消转义

result_.result(object, property) 

If the value of the named property is a function then invoke it; otherwise, return it.

var object = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }};_.result(object, 'cheese');=> "crumpets"_.result(object, 'stuff');=> "nonsense" 返回,如果这个对象的属性名是函数,则调用它,否则返回它的值

template_.template(templateString, [data], [settings]) 

Compiles JavaScript templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources. Template functions can both interpolate variables, using <%= … %>, as well as execute arbitrary JavaScript code, with <% … %>. If you wish to interpolate a value, and have it be HTML-escaped, use <%- … %> When you evaluate a template function, pass in a data object that has properties corresponding to the template's free variables. If you're writing a one-off, you can pass the data object as the second parameter to template in order to render immediately instead of returning a template function. The settings argument should be a hash containing any _.templateSettings that should be overridden.

var compiled = _.template("hello: <%= name %>");compiled({name : 'moe'});=> "hello: moe"var list = "<% _.each(people, function(name) { %> 
  • <%= name %>
  • <% }); %>";_.template(list, {people : ['moe', 'curly', 'larry']});=> "
  • moe
  • curly
  • larry
  • "var template = _.template("<%- value %>");template({value : '

    You can also use print from within JavaScript code. This is sometimes more convenient than using <%= ... %>.

    var compiled = _.template("<% print('Hello ' + epithet); %>");compiled({epithet: "stooge"});=> "Hello stooge." 模板

    If ERB-style delimiters aren't your cup of tea, you can change Underscore's template settings to use different symbols to set off interpolated code. Define an interpolateregex to match expressions that should be interpolated verbatim, an escape regex to match expressions that should be inserted after being HTML escaped, and anevaluate regex to match expressions that should be evaluated without insertion into the resulting string. You may define or omit any combination of the three. For example, to perform  style templating:

    _.templateSettings = {  interpolate : /\{\{(.+?)\}\}/g};var template = _.template("Hello {
    { name }}!");template({name : "Mustache"});=> "Hello Mustache!"

    By default, template places the values from your data in the local scope via the withstatement. However, you can specify a single variable name with the variable setting. This can significantly improve the speed at which a template is able to render.

    _.template("Using 'with': <%= data.answer %>", {answer: 'no'}, {variable: 'data'});=> "Using 'with': no"

    Precompiling your templates can be a big help when debugging errors you can't reproduce. This is because precompiled templates can provide line numbers and a stack trace, something that is not possible when compiling templates on the client. Thesource property is available on the compiled template function for easy precompilation.

    Chaining

    You can use Underscore in either an object-oriented or a functional style, depending on your preference. The following two lines of code are identical ways to double a list of numbers.

    _.map([1, 2, 3], function(n){ return n * 2; });_([1, 2, 3]).map(function(n){ return n * 2; });

    Calling chain will cause all future method calls to return wrapped objects. When you've finished the computation, use value to retrieve the final value. Here's an example of chaining together a map/flatten/reduce, in order to get the word count of every word in a song.

    var lyrics = [  {line : 1, words : "I'm a lumberjack and I'm okay"},  {line : 2, words : "I sleep all night and I work all day"},  {line : 3, words : "He's a lumberjack and he's okay"},  {line : 4, words : "He sleeps all night and he works all day"}];_.chain(lyrics)  .map(function(line) { return line.words.split(' '); })  .flatten()  .reduce(function(counts, word) {    counts[word] = (counts[word] || 0) + 1;    return counts;  }, {})  .value();=> {lumberjack : 2, all : 4, night : 2 ... }

    In addition, the  are proxied through the chained Underscore object, so you can slip a reverse or a push into your chain, and continue to modify the array.

    chain_.chain(obj) 

    Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until value is used.

    var stooges = [{name : 'curly', age : 25}, {name : 'moe', age : 21}, {name : 'larry', age : 23}];var youngest = _.chain(stooges)  .sortBy(function(stooge){ return stooge.age; })  .map(function(stooge){ return stooge.name + ' is ' + stooge.age; })  .first()  .value();=> "moe is 21" 链式调用.

    value_(obj).value() 

    Extracts the value of a wrapped object.

    _([1, 2, 3]).value();=> [1, 2, 3] 从包装对象中解板值.

    一些相关连接和推荐阅读

    The Underscore documentation is also available in .

    , a Lua port of the functions that are applicable in both languages. Includes OOP-wrapping and chaining. ()

    , an Objective-C port of many of the Underscore.js functions, using a syntax that encourages chaining. ()

    , an alternative Objective-C port that tries to stick a little closer to the original Underscore.js API. ()

    , a PHP port of the functions that are applicable in both languages. Includes OOP-wrapping and chaining. ()

    , a Perl port of many of the Underscore.js functions, aimed at on Perl hashes and arrays. ()

    , a Coldfusion port of many of the Underscore.js functions. ()

    , an Underscore extension that adds functions for string-manipulation:trimstartsWithcontainscapitalizereversesprintf, and more.

    Ruby's  module.

    , which provides JavaScript with collection functions in the manner closest to Ruby's Enumerable.

    Oliver Steele's , which includes comprehensive higher-order function support as well as string lambdas.

    Michael Aufreiter's , a data manipulation + persistence library for JavaScript.

    Python's .

    转载地址:http://frvkm.baihongyu.com/

    你可能感兴趣的文章
    git 解决冲突
    查看>>
    Android项目实战(三十四):蓝牙4.0 BLE 多设备连接
    查看>>
    使用SQL Server Management Studio 创建数据库备份作业
    查看>>
    为电子书包配置透明网关+缓存服务器
    查看>>
    鸟哥的Linux私房菜:基础学习篇 —— 第五章笔记
    查看>>
    Zabbix触发器函数(取前后差值)
    查看>>
    『算法设计_伪代码』线性时间排序及排序算法对比
    查看>>
    如何通俗理解设计模式及其思想
    查看>>
    几何画板怎么画圆锥曲线,原来这么简单
    查看>>
    编辑文章
    查看>>
    C# 操作Word 中的OLE——插入、编辑、读取 OLE
    查看>>
    [FE] 有效开展一个前端项目2 (vuejs-templates/webpack)
    查看>>
    乐鑫esp8266的串口通讯驱动源文件,nonos和rtos版本
    查看>>
    Git忽略规则和.gitignore规则不生效的解决办法
    查看>>
    6本互联网技术畅销书免费送(数据分析、深度学习、编程语言)!
    查看>>
    react-native + teaset(Drawer)实现侧边菜单
    查看>>
    WPF Dashboard仪表盘控件的实现
    查看>>
    Jvm(54),虚拟机类加载机制----类加载的过程----准备
    查看>>
    TCP/IP之大明内阁 转
    查看>>
    eclipse team 没有svn
    查看>>