一、理清概念

1、Underscore封装了常用的JavaScript对象操作方法,用于提高开发效率,Underscore还可以被使用在Node.js运行环境。从API中,你已经可以看出,Underscore没有任何复杂的结构和流程,它仅仅提供了一系列常用的函数。如果你将API中的方法从头至尾用一遍,你就会对它非常了解。

2、Underscore并没有在原生的JavaScript对象原型中进行扩展,而是像jQuery一样,将数据封装在一个自定义对象中(下文中称“Underscore对象”)。可以通过调用一个Underscore对象的value()方法来获取原生的javascript数据。

3、Underscore.js是一个很精干的库,压缩后只有4KB。它提供了几十种函数式编程的方法,弥补了标准库的不足,大大方便了JavaScript的编程。MVC框架Backbone.js就将这个库作为自己的工具库。除了可以在浏览器环境使用,Underscore.js还可以用于Node.js。Underscor.js定义了一个下划线(_)对象,函数库的所有方法都属于这个对象。这些方法大致上可以分成:集合(collection)、数组(array)、函数(function)、对象(object)和工具(utility)五大类。

二、常用库函数

1、 集合部分: 数组或对象

Javascript语言的数据集合,包括两种结构:数组和对象。以下的方法同时适用于这两种结构。

新建一个collection.js文件,测试underscore对集合的支持。

  1. ~ vi collection.js
  2. //加载underscore库
  3. var _ = require("underscore")._;

each: 对集合循环操作

  1. _.each([1, 2, 3], function (ele, idx) {
  2. console.log(idx + ":" + ele);
  3. });
  4. => 0:1
  5. 1:2
  6. 2:3

map: 对集合以map方式遍历,产生一个新数组

  1. console.log(
  2. _.map([1, 2, 3], function(num){
  3. return num * 3;
  4. })
  5. );
  6. => [3, 6, 9]

reduce: 集合元素合并集的到memo

  1. console.log(
  2. _.reduce([1, 2, 3], function (memo, num) {
  3. return memo + num;
  4. }, 0)
  5. );
  6. => 6

filter: 过滤集合中符合条件的元素。注:find:只返回第一个

  1. console.log(
  2. _.filter([1, 2, 3, 4, 5, 6], function(num){
  3. return num % 2 == 0;
  4. })
  5. );
  6. => [ 2, 4, 6 ]

reject: 过滤集合中不符合条件的元素

  1. console.log(
  2. _.reject([1, 2, 3, 4, 5, 6], function(num){
  3. return num % 2 == 0;
  4. })
  5. );
  6. => [ 1, 3, 5 ]

where: 遍历list, 返回新的对象数组

  1. var list = [
  2. {title:"AAA",year: 1982},
  3. {title:"BBB",year: 1900},
  4. {title:"CCC",year: 1982}
  5. ];
  6. console.log(
  7. _.where(list,{year: 1982})
  8. );
  9. => [ { title: 'AAA', year: 1982 }, { title: 'CCC', year: 1982 } ]

contains:判断元素是否在list中

  1. console.log(
  2. _.contains([1, 2, 3], 3)
  3. );

invoke:通过函数名调用函数运行

  1. console.log(
  2. _.invoke([[5, 1, 7]], 'sort')
  3. );
  4. => [ [ 1, 5, 7 ] ]

pluck: 提取一个集合里指定的属性值

  1. var users = [
  2. {name: 'moe', age: 40},
  3. {name: 'larry', age: 50}
  4. ];
  5. console.log(
  6. _.pluck(users, 'name')
  7. );
  8. => [ 'moe', 'larry' ]

max,min,sortBy: 取list中的最大,最小元素,自定义比较器

  1. console.log(
  2. _.max(users, function (stooge) {
  3. return stooge.age;
  4. })
  5. );
  6. => { name: 'larry', age: 50 }
  7. var numbers = [10, 5, 100, 2, 1000];
  8. console.log(
  9. _.min(numbers)
  10. );
  11. => 2
  12. console.log(
  13. _.sortBy([3, 4, 2, 1 , 6], function (num) {
  14. return Math.max(num);
  15. })
  16. );
  17. => [ 1, 2, 3, 4, 6 ]

groupBy: 把一个集合分组成多个集合

  1. console.log(
  2. _.groupBy(['one', 'two', 'three'], 'length')
  3. );
  4. => { '3': [ 'one', 'two' ], '5': [ 'three' ] }

countBy: 把一个数据分组后计数

  1. onsole.log(
  2. _.countBy([1, 2, 3, 4, 5], function (num) {
  3. return num % 2 == 0 ? 'even' : 'odd';
  4. })
  5. );
  6. => { odd: 3, even: 2 }

shuffle: 随机打乱一个数据

  1. console.log(
  2. _.shuffle([1, 2, 3, 4, 5, 6])
  3. );
  4. => [ 1, 5, 2, 3, 6, 4 ]

toArray: 将list转换成一个数组

  1. console.log(
  2. (function () {
  3. return _.toArray(arguments).slice(1);
  4. })(1, 2, 3, 4)
  5. );
  6. => [ 2, 3, 4 ]

size: 得到list中元素个数

  1. console.log(
  2. _.size({one: 1, two: 2, three: 3})
  3. );

2、数组部分

新建一个array.js

  1. ~ vi array.js
  2. var _ = require("underscore")._;

first,last,initial,rest: 数组的元素操作。

  1. var nums = [5, 4, 3, 2, 1];
  2. console.log(_.first(nums));
  3. console.log(_.last(nums));
  4. console.log(_.initial(nums,1));
  5. console.log(_.rest(nums,1));
  6. => 5
  7. 1
  8. [ 5, 4, 3, 2 ]
  9. [ 4, 3, 2, 1 ]

indexOf,lastIndexOf,sortedIndex:取索引位置

  1. console.log(_.indexOf([4, 2, 3, 4, 2], 4));
  2. console.log(_.lastIndexOf([4, 2, 3, 4, 2], 4));
  3. console.log(_.sortedIndex([10, 20, 30, 40, 50], 35));
  4. => 0
  5. 3
  6. 3

range: 创建一个范围整数数组

  1. console.log(_.range(1,10));
  2. console.log(_.range(0, -10, -1));
  3. => [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
  4. [ 0, -1, -2, -3, -4, -5, -6, -7, -8, -9 ]

compact:数组去除空值

  1. console.log(
  2. _.compact([0, 1, false, 2, '', 3])
  3. );
  4. => [ 1, 2, 3 ]

flatten:将一个嵌套多层的数组(嵌套可以是任何层数)转换为只有一层的数组

  1. console.log(
  2. _.flatten([1, [2], [3, [[4]]]])
  3. );
  4. => [ 1, 2, 3, 4 ]

without: 去掉元素

  1. console.log(
  2. _.without([1, 2, 1, 0, 3, 1, 4], 0,1 )
  3. );
  4. => [ 2, 3, 4 ]

union,intersection,difference,uniq: 并集,交集,差集,取唯一

  1. console.log(_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]));
  2. console.log(_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]));
  3. console.log(_.difference([1, 2, 3, 4, 5], [5, 2, 10]));
  4. console.log(_.uniq([1, 2, 1, 3, 1, 2]));
  5. => [ 1, 2, 3, 101, 10 ]
  6. [ 1, 2 ]
  7. [ 1, 3, 4 ]
  8. [ 1, 2, 3 ]

zip: 合并多个数组中的元素,是group的反向操作

  1. console.log(
  2. _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false])
  3. );
  4. => [ [ 'moe', 30, true ],
  5. [ 'larry', 40, false ],
  6. [ 'curly', 50, false ] ]

object: 把数组转换成对象

  1. console.log(
  2. _.object(['moe', 'larry', 'curly'], [30, 40, 50])
  3. );
  4. => { moe: 30, larry: 40, curly: 50 }

3、函数部分

新建一个function.js

  1. ~ vi function.js
  2. var _ = require("underscore")._;

bind: 绑定函数到对象上, 无论何时函数被调用, 函数里的this都指向对象.

  1. var func = function(greeting){ return greeting + ': ' + this.name };
  2. func = _.bind(func, {name : 'moe'}, 'hi');
  3. console.log(func());
  4. => hi: moe

bindAll: 绑定方法名到对象上, 当这些方法被执行时将在对象的上下文执行. 绑定函数用作事件处理时非常方便, 否则函数调用时 this 关键字根本没什么用.

  1. var buttonView = {
  2. label : 'underscore',
  3. onClick : function(){ console.log('clicked: ' + this.label); },
  4. onHover : function(){ console.log('hovering: ' + this.label); }
  5. };
  6. var func = _.bindAll(buttonView, 'onClick', 'onHover');
  7. func.onClick();
  8. => clicked: underscore

partial:在不改变this的情况下,通过参数填充数据

  1. var add = function(a, b) { return a + b; };
  2. add5 = _.partial(add, 5);
  3. console.log(add5(10));
  4. => 15

memoize: 通过缓存计算结果使函数具有记忆功能。

  1. var fibonacci = _.memoize(function(n) {
  2. return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
  3. });
  4. console.log(fibonacci(10));
  5. => 55

delay: 在等待xx毫秒之后调用函数,类似于setTimeout

  1. var log = _.bind(console.log, console);
  2. _.delay(log, 1000, 'sleep 1s');
  3. => sleep 1s

defer: 延迟调用函数, 直到当前调用栈被清空为止, 跟使用 setTimeout 赋予0毫秒的延时很像. 对执行高消耗算法或大型HTML呈现而不阻碍UI更新线程很有用.

  1. _.defer(function(){ console.log('deferred'); });
  2. => deferred

throttle:返回一个类似于节流阀一样的函数, 当高频率的调用函数, 实际上会每隔 wait 毫秒才会调用一次. 对于高到您感觉不到的高频率执行的函数时非常有用.

  1. var throttled = _.throttle(function(){
  2. _(5).times(function(n){ console.log(n+":"+new Date()); });
  3. }, 100);
  4. throttled();
  5. => 0:Wed Aug 28 2013 14:20:48 GMT+0800
  6. 1:Wed Aug 28 2013 14:20:48 GMT+0800
  7. 2:Wed Aug 28 2013 14:20:48 GMT+0800
  8. 3:Wed Aug 28 2013 14:20:48 GMT+0800
  9. 4:Wed Aug 28 2013 14:20:48 GMT+0800

debounce: 返回函数的防反跳版本, 将延迟函数的执行(真正的执行)在函数最后一次调用时刻的等待xx毫秒之后,可以实现延迟加载。

  1. var lazyLoad = _.debounce(function(){
  2. console.log("lazy load 3s");
  3. }, 3000);
  4. lazyLoad();
  5. => lazy load 3s

once: 创建一个只能运行一次的函数. 重复调用此修改过的函数会没有效果, 只会返回第一次执行时返回的结果。单例模式。

  1. var initialize = _.once(function(){console.log('initialize');});
  2. initialize();
  3. initialize();
  4. => initialize

after: 对循环计数,只有超过计数,才会调用指定的函数

  1. var nums = [1,2,3,4];
  2. var renderNums = _.after(nums.length, function(){
  3. console.log('render nums');
  4. });
  5. _.each(nums, function(num) {
  6. console.log('each:'+num);
  7. renderNums();
  8. });
  9. => each:1
  10. each:2
  11. each:3
  12. each:4
  13. render nums

wrap: 以函数作为函数传递,可以增加函数调用前后的控制。有点类似于 “模板方法模式”

  1. var hello = function(name) { return "hello: " + name; };
  2. hello = _.wrap(hello, function(func) {
  3. return "before, " + func("moe") + ", after";
  4. });
  5. console.log(hello());
  6. => before, hello: moe, after

compose: 组合函数调用关系,把单独的f(),g(),h()组合成f(g(h()))

  1. var greet = function(name){ return "A: " + name; };
  2. var exclaim = function(statement){ return "B: "+statement + "!"; };
  3. var welcome = _.compose(exclaim, greet);
  4. console.log(welcome('moe'));
  5. => B: A: moe!

4、对象部分

新建一个object.js

  1. ~ vi object.js
  2. var _ = require("underscore")._;

keys,values,paris,invert: 取属性名,取属性值,把对象转换成[key,value]数组,对调键值

  1. var obj = {one: 1, two: 2, three: 3}
  2. console.log(_.keys(obj));
  3. console.log(_.values(obj));
  4. console.log(_.pairs(obj));
  5. console.log(_.invert(obj));
  6. => [ 'one', 'two', 'three' ]
  7. [ 1, 2, 3 ]
  8. [ [ 'one', 1 ], [ 'two', 2 ], [ 'three', 3 ] ]
  9. { '1': 'one', '2': 'two', '3': 'three' }

functions:返回对象的所有方法名

  1. var fun = {
  2. fun1:function(){},
  3. fun2:function(){}
  4. }
  5. console.log(_.functions(fun));
  6. => [ 'fun1', 'fun2' ]

extend: 复制对象的所有属性到目标对象上,覆盖已有属性

  1. console.log(
  2. _.extend({name : 'moe'}, {age : 50})
  3. );
  4. => { name: 'moe', age: 50 }

defaults: 复制对象的所有属性到目标对象上,跳过已有属性

  1. var iceCream = {flavor : "chocolate"};
  2. console.log(
  3. _.defaults(iceCream, {flavor : "vanilla", sprinkles : "lots"})
  4. );
  5. => { flavor: 'chocolate', sprinkles: 'lots' }

pick,omit: 返回一个对象的副本,保留指定的属性或去掉指定的属性

  1. console.log(
  2. _.pick({name : 'moe', age: 50, userid : 'moe1'}, 'name', 'age')
  3. );
  4. => { name: 'moe', age: 50 }
  5. console.log(
  6. _.omit({name : 'moe', age : 50, userid : 'moe1'}, 'userid')
  7. );
  8. => { name: 'moe', age: 50 }

clone: 引入方式克隆对象,不进行复制

  1. console.log(
  2. _.clone({name : 'moe'});
  3. );
  4. => {name : 'moe'};

tag: 用对象作为参数来调用函数,作为函数链式调用的一环

  1. console.log(
  2. _.chain([1,2,3,200])
  3. .filter(function(num) { return num % 2 == 0; })
  4. .tap(console.log)
  5. .map(function(num) { return num * num })
  6. .value()
  7. );
  8. => [ 2, 200 ]
  9. [ 4, 40000 ]

has: 判断对象是否包含指定的属性名

  1. console.log(_.has({a: 1, b: 2, c: 3}, "b"));

isEqual: 判断两个对象是值相等

  1. var moe = {name : 'moe', luckyNumbers : [13, 27, 34]};
  2. var clone = {name : 'moe', luckyNumbers : [13, 27, 34]};
  3. console.log(moe == clone);
  4. => false
  5. console.log(_.isEqual(moe, clone));
  6. => true

判断对象类型的方法,下面反回值都是true

  1. console.log(_.isEmpty({}));
  2. console.log(_.isArray([1,2,3]));
  3. console.log(_.isObject({}));
  4. console.log((function(){ return _.isArguments(arguments); })(1, 2, 3));
  5. console.log(_.isFunction(console.log));
  6. console.log(_.isString("moe"));
  7. console.log(_.isNumber(8.4 * 5));
  8. console.log(_.isFinite(-101));
  9. console.log(_.isBoolean(true));
  10. console.log(_.isDate(new Date()));
  11. console.log(_.isNaN(NaN));
  12. console.log(_.isNull(null));
  13. console.log(_.isUndefined(undefined));
  14. => true

5、实用功能

新建一个util.js

  1. ~ vi util.js
  2. var _ = require("underscore")._;

noConflict: 把 “_” 变量的控制权预留给它原有的所有者. 返回一个引用给 Underscore 对象.

  1. var underscore = _.noConflict();

identity: 返回与传入参数相等的值. 相当于数学里的: f(x) = x

  1. var moe = {name : 'moe'};
  2. console.log(moe === _.identity(moe));
  3. => true

times: 设计调用次数

  1. _(3).times(function(n){ console.log(n); });
  2. => 0
  3. 1
  4. 2

random: 返回范围内的随机数

  1. console.log(_.random(0, 100));
  2. => 30

mixin: 封装自己的函数到Underscore对象中,后面Underscore.string就是这种方式的集成

  1. _.mixin({
  2. capitalize : function(string) {
  3. return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
  4. }
  5. });
  6. console.log(_("fabio").capitalize());
  7. => Fabio

uniqueId:产生一个全局的唯一id,以参数作为前缀

  1. console.log(_.uniqueId('contact_'));
  2. => contact_1
  3. console.log(_.uniqueId('contact_'));
  4. => contact_2

escape,unescape:转义HTML字符串,反转到HTML字符串

  1. console.log(_.escape('Curly, Larry & Moe'));
  2. => Curly, Larry &amp; Moe
  3. console.log(_.unescape('Curly, Larry &amp; Moe'));
  4. => Curly, Larry & Moe

result: 通过字符串调用对象的函数,或返回属性值

  1. var obj = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }};
  2. console.log(_.result(obj, 'cheese'));
  3. => crumpets
  4. console.log(_.result(obj, 'stuff'));
  5. => nonsense

template: 将 JavaScript 模板编译为可以用于页面呈现的函数, 对于通过JSON数据源生成复杂的HTML并呈现出来的操作非常有用. 模板函数可以通过以下两种方式插入到页面中, 使用<%= … %>, 也可以用<% … %>执行任意的 JavaScript 代码. 如果您希望插入一个值, 并让其进行HTML转义, 当您使用创建一个模板时使用 <%- … %> , 传入一个含有与模板对应属性的对象 data. 如果您要写一个一次性的, 您可以传对象 data 作为第二个参数给模板template 来直接呈现, 这样页面会立即呈现而不是返回一个模板函数. 参数 settings 是一个哈希表包含任何可以覆盖的设置 _.templateSettings.

  1. var compiled = _.template("hello: <%= name %>");
  2. console.log(compiled({name : 'moe'}));
  3. =>hello: moe
  4. var list = "<% _.each(people, function(name) { %> <li><%= name %></li> <% }); %>";
  5. console.log(_.template(list, {people : ['moe', 'curly', 'larry']}));
  6. => <li>moe</li> <li>curly</li> <li>larry</li>
  7. var template = _.template("<b><%- value %></b>");
  8. console.log(template({value : '<script>'}));
  9. => <b>&lt;script&gt;</b>
  10. var compiled = _.template("<% print('Hello ' + epithet); %>");
  11. console.log(compiled({epithet: "stooge"}));
  12. =>Hello stooge
  13. console.log(_.template("Using 'with': <%= data.answer %>", {answer: 'no'}, {variable: 'data'}));
  14. =>Using 'with': no
  15. _.templateSettings = {
  16. interpolate : /\{\{(.+?)\}\}/g
  17. };
  18. var template = _.template("Hello {{ name }}!");
  19. console.log(template({name : "Mustache"}));
  20. =>Hello Mustache!

6、链式语法

新建一个chaining.js

  1. ~ vi chaining.js
  2. var _ = require("underscore")._;

chain: 返回一个封装的对象. 在封装的对象上调用方法会返回封装的对象本身, 直到value() 方法调用为止.

  1. var stooges = [{name : 'curly', age : 25}, {name : 'moe', age : 21}, {name : 'larry', age : 23}];
  2. var youngest = _.chain(stooges)
  3. .sortBy(function(stooge){ return stooge.age; })
  4. .map(function(stooge){ return stooge.name + ' is ' + stooge.age; })
  5. .first()
  6. .value();
  7. console.log(youngest);
  8. => moe is 21

对一个对象使用 chain 方法, 会把这个对象封装并 让以后每次方法的调用结束后都返回这个封装的对象, 当您完成了计算, 可以使用 value 函数来取得最终的值. 以下是一个同时使用了 map/flatten/reduce 的链式语法例子, 目的是计算一首歌的歌词里每一个单词出现的次数.

  1. var lyrics = [
  2. {line : 1, words : "I'm a lumberjack and I'm okay"},
  3. {line : 2, words : "I sleep all night and I work all day"},
  4. {line : 3, words : "He's a lumberjack and he's okay"},
  5. {line : 4, words : "He sleeps all night and he works all day"}
  6. ];
  7. console.log(
  8. _.chain(lyrics)
  9. .map(function(line) { return line.words.split(' '); })
  10. .flatten()
  11. .reduce(function(counts, word) {
  12. counts[word] = (counts[word] || 0) + 1;
  13. return counts;
  14. }, {})
  15. .value()
  16. );
  17. => { 'I\'m': 2,
  18. a: 2,
  19. lumberjack: 2,
  20. and: 4,
  21. okay: 2,
  22. I: 2,
  23. sleep: 1,
  24. all: 4,
  25. night: 2,
  26. work: 1,
  27. day: 2,
  28. 'He\'s': 1,
  29. 'he\'s': 1,
  30. He: 1,
  31. sleeps: 1,
  32. he: 1,
  33. works: 1 }

value: 提取封装对象的最终值,作为chain()结束标志。

  1. console.log(_([1, 2, 3]).value());

7、字符串处理Underscore.String

安装underscore.string

  1. ~ D:\workspace\javascript\nodejs-underscore>npm install underscore.string
  2. npm http GET https://registry.npmjs.org/underscore.string
  3. npm http 304 https://registry.npmjs.org/underscore.string
  4. underscore.string@2.3.3 node_modules\underscore.string

新建一个string.js,通过mixin()函数,让underscore.string和underscore集成统计实现_.fun()语法。

  1. ~ vi string.js
  2. var _ = require('underscore');
  3. _.str = require('underscore.string');
  4. _.mixin(_.str.exports());

字符串的数字格式化

  1. console.log(_.numberFormat(1000, 2));
  2. => 1,000.00
  3. console.log(_.numberFormat(123456789.123, 5, '.', ','));
  4. => 123,456,789.12300
  5. console.log(_('2.556').toNumber());
  6. => 3
  7. console.log(_('2.556').toNumber(2));
  8. => 2.56
  9. console.log(_.sprintf("%.1f", 1.17));
  10. => 1.2

字符串基础操作

  1. console.log(_.levenshtein('kitten', 'kittah'));
  2. => 2
  3. console.log(_.capitalize('epeli'));
  4. => Epeli
  5. console.log(_.chop('whitespace', 3));
  6. => [ 'whi', 'tes', 'pac', 'e' ]
  7. console.log(_.clean(" foo bar "));
  8. => foo bar
  9. console.log(_.chars('Hello'));
  10. => [ 'H', 'e', 'l', 'l', 'o' ]
  11. console.log(_.swapCase('hELLO'));
  12. => Hello
  13. console.log(_.str.include("foobar", "ob")); //不兼容API,需要用_.str.fun()
  14. => true
  15. console.log(_.str.reverse("foobar"));//不兼容API,需要用_.str.fun()
  16. => raboof
  17. console.log(_('Hello world').count('l'));
  18. => 3
  19. console.log(_('Hello ').insert(6, 'world'));
  20. => Hello world
  21. console.log(_('').isBlank() && _('\n').isBlank() && _(' ').isBlank());
  22. => true
  23. console.log(_.join(",", "foo", "bar"));
  24. => foo,bar
  25. console.log(_.lines("Hello\nWorld"));
  26. => [ 'Hello', 'World' ]
  27. console.log(_("image.gif").startsWith("image"));
  28. => true
  29. console.log(_("image.gif").endsWith("gif"));
  30. => true
  31. console.log(_('a').succ());//指下编码的下一个
  32. => b

字符串变换

  1. console.log(_.repeat("foo", 3));
  2. => foofoofoo
  3. console.log(_.repeat("foo", 3, "bar"));
  4. => foobarfoobarfoo
  5. console.log(_.surround("foo", "ab"));
  6. => abfooab
  7. console.log(_.quote('foo', "#"));
  8. => #foo#
  9. console.log(_.unquote('"foo"'));
  10. => foo
  11. console.log(_.unquote("'foo'", "'"));
  12. => foo
  13. console.log(_.slugify("Un éléphant à l'orée du bois"));
  14. => un-elephant-a-loree-du-bois
  15. console.log(['foo20', 'foo5'].sort(_.naturalCmp));
  16. => [ 'foo5', 'foo20' ]
  17. console.log(_.toBoolean("true"));
  18. => true
  19. console.log(_.toBoolean("truthy", ["truthy"], ["falsy"]));
  20. => true
  21. console.log(_.toBoolean("true only at start", [/^true/]));
  22. => true

字符串替换,截断

  1. console.log(_('https://edtsech@bitbucket.org/edtsech/underscore.strings').splice(30, 7, 'epeli'));
  2. => https://edtsech@bitbucket.org/epeli/underscore.strings
  3. console.log(_.trim(" foobar "));
  4. => foobar
  5. console.log(_.trim("_-foobar-_", "_-"));
  6. => foobar
  7. console.log(_('Hello world').truncate(5));
  8. => Hello...
  9. console.log(_('Hello, world').prune(5));
  10. => Hello...
  11. console.log(_('Hello, world').prune(5, ' (read a lot more)'));
  12. => Hello, world
  13. console.log(_.words(" I love you "));
  14. => [ 'I', 'love', 'you' ]
  15. console.log(_.words("I-love-you", /-/));
  16. => [ 'I', 'love', 'you' ]
  17. console.log(_('This_is_a_test_string').strRight('_'));
  18. => is_a_test_string
  19. console.log(_('This_is_a_test_string').strRightBack('_'));
  20. => string
  21. console.log(_('This_is_a_test_string').strLeft('_'));
  22. => This
  23. console.log(_('This_is_a_test_string').strLeftBack('_'));
  24. => This_is_a_test

字符串占位

  1. console.log(_.pad("1", 8));
  2. => 1
  3. console.log(_.pad("1", 8, '0'));
  4. => 00000001
  5. console.log(_.pad("1", 8, '0', 'right'));
  6. => 10000000
  7. console.log(_.pad("1", 8, 'bleepblorp', 'both'));
  8. => bbbb1bbb
  9. console.log(_.lpad("1", 8, '0'));
  10. => 00000001
  11. console.log(_.rpad("1", 8, '0'));
  12. => 10000000
  13. console.log(_.lrpad("1", 8, '0'));
  14. => 00001000

字符串语义处理

  1. console.log(_.toSentence(['jQuery', 'Mootools', 'Prototype']));
  2. => jQuery, Mootools and Prototype
  3. console.log(_.toSentence(['jQuery', 'Mootools', 'Prototype'], ', ', ' unt '));
  4. => jQuery, Mootools unt Prototype
  5. console.log(_.toSentenceSerial(['jQuery', 'Mootools']));
  6. => jQuery and Mootools
  7. console.log(_.toSentenceSerial(['jQuery', 'Mootools', 'Prototype']));
  8. => jQuery, Mootools, and Prototype
  9. console.log(_('my name is epeli').titleize());
  10. => My Name Is Epeli
  11. console.log(_('-moz-transform').camelize());
  12. => MozTransform
  13. console.log(_('some_class_name').classify());
  14. => SomeClassName
  15. console.log(_('MozTransform').underscored());
  16. => moz_transform
  17. console.log(_('MozTransform').dasherize());
  18. => -moz-transform
  19. console.log(_(' capitalize dash-CamelCase_underscore trim ').humanize());
  20. => Capitalize dash camel case underscore trim

HTML相关操作

  1. console.log(_('<div>Blah blah blah</div>').escapeHTML());
  2. => &lt;div&gt;Blah blah blah&lt;/div&gt;
  3. console.log(_('&lt;div&gt;Blah blah blah&lt;/div&gt;').unescapeHTML());
  4. =><div>Blah blah blah</div>
  5. console.log(_('a <a href="#">link</a>').stripTags());
  6. =>a link
  7. console.log(_('a <a href="#">link</a><script>alert("hello world!")</script>').stripTags());
  8. =>a linkalert("hello world!")

三、underscore.string.js

version:   underscore.string 3.2.1 | MIT licensed | http://epeli.github.com/underscore.string/

  1. <script src="underscore.js"></script>
  2. <script src="underscore.string.js"></script>
  3. <script type="text/javascript">
  4. console.log(s.exports());
  5. _.mixin(s.exports());
  6. alert(_.capitalize("sdfds"));
  7. </script>

或者

  1. <script src="underscore.string.js"></script>
  2. <script type="text/javascript">
  3. console.log(s.capitalize("fuckit"));
  4. </script>

说明underscore.string.js可以独立于underscore.js存在,会暴露出s全局变量。

转自 http://blog.csdn.net/qhairen/article/details/49447787

underscore.js学习笔记的更多相关文章

  1. 【转】Backbone.js学习笔记(二)细说MVC

    文章转自: http://segmentfault.com/a/1190000002666658 对于初学backbone.js的同学可以先参考我这篇文章:Backbone.js学习笔记(一) Bac ...

  2. js学习笔记:webpack基础入门(一)

    之前听说过webpack,今天想正式的接触一下,先跟着webpack的官方用户指南走: 在这里有: 如何安装webpack 如何使用webpack 如何使用loader 如何使用webpack的开发者 ...

  3. Vue.js学习笔记(2)vue-router

    vue中vue-router的使用:

  4. JS 学习笔记--9---变量-作用域-内存相关

    JS 中变量和其它语言中变量最大的区别就是,JS 是松散型语言,决定了它只是在某一个特定时间保存某一特定的值的一个名字而已.由于在定义变量的时候不需要显示规定必须保存某种类型的值,故变量的值以及保存的 ...

  5. WebGL three.js学习笔记 使用粒子系统模拟时空隧道(虫洞)

    WebGL three.js学习笔记 使用粒子系统模拟时空隧道 本例的运行结果如图: 时空隧道demo演示 Demo地址:https://nsytsqdtn.github.io/demo/sprite ...

  6. WebGL three.js学习笔记 法向量网格材质MeshNormalMaterial的介绍和创建360度全景天空盒的方法

    WebGL学习----Three.js学习笔记(5) 点击查看demo演示 Demo地址:https://nsytsqdtn.github.io/demo/360/360 简单网格材质 MeshNor ...

  7. WebGL three.js学习笔记 创建three.js代码的基本框架

    WebGL学习----Three.js学习笔记(1) webgl介绍 WebGL是一种3D绘图协议,它把JavaScript和OpenGL ES 2.0结合在一起,通过增加OpenGL ES 2.0的 ...

  8. vue.js 学习笔记3——TypeScript

    目录 vue.js 学习笔记3--TypeScript 工具 基础类型 数组 元组 枚举 字面量 接口 类类型 类类型要素 函数 函数参数 this对象和类型 重载 迭代器 Symbol.iterat ...

  9. 2019-4-29 js学习笔记

    js学习笔记一:js数据类型   1:基本数据类型       number类型(整数,小数)      String类型          boolean类型        NaN类型其实是一个nu ...

随机推荐

  1. redis5.0.0.版设置开机自启

  2. 利用svg描边+css3实现边框逐渐消失小动画

    首先简单的描述一下svg中两个属性: stroke-dasharray:表示每个虚线的长短. stroke-dashoffset:表示首个虚线的偏移量. 当两者都特别大的时候就会消失掉 直接上代码: ...

  3. ORM(二)

    一.ORM简介         对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术.简单的说,ORM是通过使 ...

  4. 2009 ACM 水题

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=2009 思路:寻找平方根的函数,c++里面有sqrt,一定要注意 1 添加头文件#include <i ...

  5. [PA2014]Kuglarz

    [PA2014]Kuglarz 题目大意: 有一个长度为\(n(n\le2000)\)的0/1串,你可以花\(c_{i,j}\)的钱,询问区间\([i,j]\)的异或和.问至少要多少元才能知道原来的序 ...

  6. 面试知识点——Java

    目录 Java容器 hashmap实现原理 java多线程 jvm内存模型 java 垃圾回收机制 对象存活状态检查 垃圾收集算法 垃圾收集器 内存分配与回收策略 java nio Java容器 ha ...

  7. sublime Text3 插件

    sublime  Text3 插件大全以及使用方法 参考网址: https://www.cnblogs.com/qqing/p/6872195.html

  8. python之模块4

    1 模块与包 1.1 模块的定义 什么是模块 模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 为什么使用模块 在退出python解释器然后重新进入,之前定义的函数 ...

  9. elastic-job详解(一):数据分片

    数据分片的目的在于把一个任务分散到不同的机器上运行,既可以解决单机计算能力上限的问题,也能降低部分任务失败对整体系统的影响.elastic-job并不直接提供数据处理的功能,框架只会将分片项分配至各个 ...

  10. C_关于递归算法的几个例子

    1.递归算法的定义: 2.递归与迭代的优劣 eg1:斐波那契数列:斐波那契数列(Fibonacci sequence),又称黄金分割数列.因数学家列昂纳多·斐波那契(Leonardoda Fibona ...