Underscore使用方法

从其他语言转向Javascript时,通常都会遇到一些困惑性问题。比如,Java中的HashMap在Javascript中如何实现?Javascript面向对象式编程如何实现继承?如何实现通用的iterator对集合对象做遍历?如何对Array实现快速排序?….

如果你真的可以自己实现这些功能,那么你的Javascript基础很扎实的!我很佩服你!但对于大部分人来说,这些基础功能应该是由底层API支持的,就像JDK一样。Underscore为我们提供了这样的一个实用工具包,而且它真的很实用!

只有你动手做了,你才能有收获。

目录

  1. Underscore介绍
  2. Underscore安装
  3. 集合部分:数组或对象
  4. 数组部分
  5. 函数部分
  6. 对象部分
  7. 实用功能
  8. 链式语法
  9. 字符串处理Underscore.String

1. Underscore介绍

Underscore 是一个JavaScript实用库,提供了类似Prototype.js的一些功能,但是没有继承任何JavaScript内置对象。它弥补了部分jQuery没有实现的功能,同时又是Backbone.js必不可少的部分。

Underscore提供了80多个函数,包括常用的: map, select, invoke — 当然还有更多专业的辅助函数,如:函数绑定, JavaScript模板功能, 强类型相等测试, 等等. 在新的浏览器中, 有许多函数如果浏览器本身直接支持,将会采用原生的,如 forEach, map, reduce, filter, every, some 和 indexOf.

Underscore介绍来自官方文档,Underscore.js (1.7.0) 中文API文档:http://www.css88.com/doc/underscore/

2. Underscore安装

Underscore.js是一个Javascript功能类库,不依赖于环境,可以加载到HTML中在浏览器运行,也可以直接在nodejs的环境中使用。

为了方便介绍函数功能,我这里选择在nodejs的环境中运行。

我的系统环境

 
 
  1. win7 64bit, node v0.10.5, npm 1.2.19

安装Underscore

 
 
  1. ~ D:\workspace\javascript>mkdir nodejs-underscore
  2. ~ D:\workspace\javascript>cd nodejs-underscore
  3.  
  4. ~ D:\workspace\javascript\nodejs-underscore>npm install underscore
  5. npm http GET https://registry.npmjs.org/underscore
  6. npm http 304 https://registry.npmjs.org/underscore
  7. npm http GET https://registry.npmjs.org/underscore/-/underscore-1.5.1.tgz
  8. npm http 200 https://registry.npmjs.org/underscore/-/underscore-1.5.1.tgz
  9. underscore@1.5.1 node_modules\underscore

underscore有80多的函数,下面我只介绍一些,我比较感兴趣的,实用的。

3. 集合部分: 数组或对象

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

 
 
  1. ~ vi collection.js
  2.  
  3. //加载underscore库
  4. 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.  
  8. var numbers = [10, 5, 100, 2, 1000];
  9. console.log(
  10. _.min(numbers)
  11. );
  12. => 2
  13.  
  14. console.log(
  15. _.sortBy([3, 4, 2, 1 , 6], function (num) {
  16. return Math.max(num);
  17. })
  18. );
  19. => [ 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. );

4. 数组部分

新建一个array.js

 
 
  1. ~ vi array.js
  2.  
  3. 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 }

5. 函数部分

新建一个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!

6. 对象部分

新建一个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

7. 实用功能

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

8. 链式语法

新建一个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());

9. 字符串处理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.  
  3. var _ = require('underscore');
  4. _.str = require('underscore.string');
  5. _.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!")
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值