一、理清概念
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、 集合部分: 數組或對象
新建一個collection.js文件,測試underscore對集合的支持。
- ~ vi collection.js
- //加載underscore庫
- var _ = require("underscore")._;
each: 對集合循環操作
- _.each([1, 2, 3], function (ele, idx) {
- console.log(idx + ":" + ele);
- });
- => 0:1
- 1:2
- 2:3
map: 對集合以map方式遍歷,產生一個新數組
- console.log(
- _.map([1, 2, 3], function(num){
- return num * 3;
- })
- );
- => [3, 6, 9]
reduce: 集合元素合並集的到memo
- console.log(
- _.reduce([1, 2, 3], function (memo, num) {
- return memo + num;
- }, 0)
- );
- => 6
filter: 過濾集合中符合條件的元素。注:find:只返回第一個
- console.log(
- _.filter([1, 2, 3, 4, 5, 6], function(num){
- return num % 2 == 0;
- })
- );
- => [ 2, 4, 6 ]
reject: 過濾集合中不符合條件的元素
- console.log(
- _.reject([1, 2, 3, 4, 5, 6], function(num){
- return num % 2 == 0;
- })
- );
- => [ 1, 3, 5 ]
where: 遍歷list, 返回新的對象數組
- var list = [
- {title:"AAA",year: 1982},
- {title:"BBB",year: 1900},
- {title:"CCC",year: 1982}
- ];
- console.log(
- _.where(list,{year: 1982})
- );
- => [ { title: 'AAA', year: 1982 }, { title: 'CCC', year: 1982 } ]
contains:判斷元素是否在list中
- console.log(
- _.contains([1, 2, 3], 3)
- );
invoke:通過函數名調用函數運行
- console.log(
- _.invoke([[5, 1, 7]], 'sort')
- );
- => [ [ 1, 5, 7 ] ]
pluck: 提取一個集合里指定的屬性值
- var users = [
- {name: 'moe', age: 40},
- {name: 'larry', age: 50}
- ];
- console.log(
- _.pluck(users, 'name')
- );
- => [ 'moe', 'larry' ]
max,min,sortBy: 取list中的最大,最小元素,自定義比較器
- console.log(
- _.max(users, function (stooge) {
- return stooge.age;
- })
- );
- => { name: 'larry', age: 50 }
- var numbers = [10, 5, 100, 2, 1000];
- console.log(
- _.min(numbers)
- );
- => 2
- console.log(
- _.sortBy([3, 4, 2, 1 , 6], function (num) {
- return Math.max(num);
- })
- );
- => [ 1, 2, 3, 4, 6 ]
groupBy: 把一個集合分組成多個集合
- console.log(
- _.groupBy(['one', 'two', 'three'], 'length')
- );
- => { '3': [ 'one', 'two' ], '5': [ 'three' ] }
countBy: 把一個數據分組后計數
- onsole.log(
- _.countBy([1, 2, 3, 4, 5], function (num) {
- return num % 2 == 0 ? 'even' : 'odd';
- })
- );
- => { odd: 3, even: 2 }
shuffle: 隨機打亂一個數據
- console.log(
- _.shuffle([1, 2, 3, 4, 5, 6])
- );
- => [ 1, 5, 2, 3, 6, 4 ]
toArray: 將list轉換成一個數組
- console.log(
- (function () {
- return _.toArray(arguments).slice(1);
- })(1, 2, 3, 4)
- );
- => [ 2, 3, 4 ]
size: 得到list中元素個數
- console.log(
- _.size({one: 1, two: 2, three: 3})
- );
2、數組部分
新建一個array.js
- ~ vi array.js
- var _ = require("underscore")._;
first,last,initial,rest: 數組的元素操作。
- var nums = [5, 4, 3, 2, 1];
- console.log(_.first(nums));
- console.log(_.last(nums));
- console.log(_.initial(nums,1));
- console.log(_.rest(nums,1));
- => 5
- 1
- [ 5, 4, 3, 2 ]
- [ 4, 3, 2, 1 ]
indexOf,lastIndexOf,sortedIndex:取索引位置
- console.log(_.indexOf([4, 2, 3, 4, 2], 4));
- console.log(_.lastIndexOf([4, 2, 3, 4, 2], 4));
- console.log(_.sortedIndex([10, 20, 30, 40, 50], 35));
- => 0
- 3
- 3
range: 創建一個范圍整數數組
- console.log(_.range(1,10));
- console.log(_.range(0, -10, -1));
- => [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
- [ 0, -1, -2, -3, -4, -5, -6, -7, -8, -9 ]
compact:數組去除空值
- console.log(
- _.compact([0, 1, false, 2, '', 3])
- );
- => [ 1, 2, 3 ]
flatten:將一個嵌套多層的數組(嵌套可以是任何層數)轉換為只有一層的數組
- console.log(
- _.flatten([1, [2], [3, [[4]]]])
- );
- => [ 1, 2, 3, 4 ]
without: 去掉元素
- console.log(
- _.without([1, 2, 1, 0, 3, 1, 4], 0,1 )
- );
- => [ 2, 3, 4 ]
union,intersection,difference,uniq: 並集,交集,差集,取唯一
- console.log(_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]));
- console.log(_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]));
- console.log(_.difference([1, 2, 3, 4, 5], [5, 2, 10]));
- console.log(_.uniq([1, 2, 1, 3, 1, 2]));
- => [ 1, 2, 3, 101, 10 ]
- [ 1, 2 ]
- [ 1, 3, 4 ]
- [ 1, 2, 3 ]
zip: 合並多個數組中的元素,是group的反向操作
- console.log(
- _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false])
- );
- => [ [ 'moe', 30, true ],
- [ 'larry', 40, false ],
- [ 'curly', 50, false ] ]
object: 把數組轉換成對象
- console.log(
- _.object(['moe', 'larry', 'curly'], [30, 40, 50])
- );
- => { moe: 30, larry: 40, curly: 50 }
3、函數部分
新建一個function.js
- ~ vi function.js
- var _ = require("underscore")._;
bind: 綁定函數到對象上, 無論何時函數被調用, 函數里的this都指向對象.
- var func = function(greeting){ return greeting + ': ' + this.name };
- func = _.bind(func, {name : 'moe'}, 'hi');
- console.log(func());
- => hi: moe
bindAll: 綁定方法名到對象上, 當這些方法被執行時將在對象的上下文執行. 綁定函數用作事件處理時非常方便, 否則函數調用時 this 關鍵字根本沒什么用.
- var buttonView = {
- label : 'underscore',
- onClick : function(){ console.log('clicked: ' + this.label); },
- onHover : function(){ console.log('hovering: ' + this.label); }
- };
- var func = _.bindAll(buttonView, 'onClick', 'onHover');
- func.onClick();
- => clicked: underscore
partial:在不改變this的情況下,通過參數填充數據
- var add = function(a, b) { return a + b; };
- add5 = _.partial(add, 5);
- console.log(add5(10));
- => 15
memoize: 通過緩存計算結果使函數具有記憶功能。
- var fibonacci = _.memoize(function(n) {
- return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
- });
- console.log(fibonacci(10));
- => 55
delay: 在等待xx毫秒之后調用函數,類似於setTimeout
- var log = _.bind(console.log, console);
- _.delay(log, 1000, 'sleep 1s');
- => sleep 1s
defer: 延遲調用函數, 直到當前調用棧被清空為止, 跟使用 setTimeout 賦予0毫秒的延時很像. 對執行高消耗算法或大型HTML呈現而不阻礙UI更新線程很有用.
- _.defer(function(){ console.log('deferred'); });
- => deferred
throttle:返回一個類似於節流閥一樣的函數, 當高頻率的調用函數, 實際上會每隔 wait 毫秒才會調用一次. 對於高到您感覺不到的高頻率執行的函數時非常有用.
- var throttled = _.throttle(function(){
- _(5).times(function(n){ console.log(n+":"+new Date()); });
- }, 100);
- throttled();
- => 0:Wed Aug 28 2013 14:20:48 GMT+0800
- 1:Wed Aug 28 2013 14:20:48 GMT+0800
- 2:Wed Aug 28 2013 14:20:48 GMT+0800
- 3:Wed Aug 28 2013 14:20:48 GMT+0800
- 4:Wed Aug 28 2013 14:20:48 GMT+0800
debounce: 返回函數的防反跳版本, 將延遲函數的執行(真正的執行)在函數最后一次調用時刻的等待xx毫秒之后,可以實現延遲加載。
- var lazyLoad = _.debounce(function(){
- console.log("lazy load 3s");
- }, 3000);
- lazyLoad();
- => lazy load 3s
once: 創建一個只能運行一次的函數. 重復調用此修改過的函數會沒有效果, 只會返回第一次執行時返回的結果。單例模式。
- var initialize = _.once(function(){console.log('initialize');});
- initialize();
- initialize();
- => initialize
after: 對循環計數,只有超過計數,才會調用指定的函數
- var nums = [1,2,3,4];
- var renderNums = _.after(nums.length, function(){
- console.log('render nums');
- });
- _.each(nums, function(num) {
- console.log('each:'+num);
- renderNums();
- });
- => each:1
- each:2
- each:3
- each:4
- render nums
wrap: 以函數作為函數傳遞,可以增加函數調用前后的控制。有點類似於 “模板方法模式”
- var hello = function(name) { return "hello: " + name; };
- hello = _.wrap(hello, function(func) {
- return "before, " + func("moe") + ", after";
- });
- console.log(hello());
- => before, hello: moe, after
compose: 組合函數調用關系,把單獨的f(),g(),h()組合成f(g(h()))
- var greet = function(name){ return "A: " + name; };
- var exclaim = function(statement){ return "B: "+statement + "!"; };
- var welcome = _.compose(exclaim, greet);
- console.log(welcome('moe'));
- => B: A: moe!
4、對象部分
新建一個object.js
- ~ vi object.js
- var _ = require("underscore")._;
keys,values,paris,invert: 取屬性名,取屬性值,把對象轉換成[key,value]數組,對調鍵值
- var obj = {one: 1, two: 2, three: 3}
- console.log(_.keys(obj));
- console.log(_.values(obj));
- console.log(_.pairs(obj));
- console.log(_.invert(obj));
- => [ 'one', 'two', 'three' ]
- [ 1, 2, 3 ]
- [ [ 'one', 1 ], [ 'two', 2 ], [ 'three', 3 ] ]
- { '1': 'one', '2': 'two', '3': 'three' }
functions:返回對象的所有方法名
- var fun = {
- fun1:function(){},
- fun2:function(){}
- }
- console.log(_.functions(fun));
- => [ 'fun1', 'fun2' ]
extend: 復制對象的所有屬性到目標對象上,覆蓋已有屬性
- console.log(
- _.extend({name : 'moe'}, {age : 50})
- );
- => { name: 'moe', age: 50 }
defaults: 復制對象的所有屬性到目標對象上,跳過已有屬性
- var iceCream = {flavor : "chocolate"};
- console.log(
- _.defaults(iceCream, {flavor : "vanilla", sprinkles : "lots"})
- );
- => { flavor: 'chocolate', sprinkles: 'lots' }
pick,omit: 返回一個對象的副本,保留指定的屬性或去掉指定的屬性
- console.log(
- _.pick({name : 'moe', age: 50, userid : 'moe1'}, 'name', 'age')
- );
- => { name: 'moe', age: 50 }
- console.log(
- _.omit({name : 'moe', age : 50, userid : 'moe1'}, 'userid')
- );
- => { name: 'moe', age: 50 }
clone: 引入方式克隆對象,不進行復制
- console.log(
- _.clone({name : 'moe'});
- );
- => {name : 'moe'};
tag: 用對象作為參數來調用函數,作為函數鏈式調用的一環
- console.log(
- _.chain([1,2,3,200])
- .filter(function(num) { return num % 2 == 0; })
- .tap(console.log)
- .map(function(num) { return num * num })
- .value()
- );
- => [ 2, 200 ]
- [ 4, 40000 ]
has: 判斷對象是否包含指定的屬性名
- console.log(_.has({a: 1, b: 2, c: 3}, "b"));
isEqual: 判斷兩個對象是值相等
- var moe = {name : 'moe', luckyNumbers : [13, 27, 34]};
- var clone = {name : 'moe', luckyNumbers : [13, 27, 34]};
- console.log(moe == clone);
- => false
- console.log(_.isEqual(moe, clone));
- => true
判斷對象類型的方法,下面反回值都是true
- console.log(_.isEmpty({}));
- console.log(_.isArray([1,2,3]));
- console.log(_.isObject({}));
- console.log((function(){ return _.isArguments(arguments); })(1, 2, 3));
- console.log(_.isFunction(console.log));
- console.log(_.isString("moe"));
- console.log(_.isNumber(8.4 * 5));
- console.log(_.isFinite(-101));
- console.log(_.isBoolean(true));
- console.log(_.isDate(new Date()));
- console.log(_.isNaN(NaN));
- console.log(_.isNull(null));
- console.log(_.isUndefined(undefined));
- => true
5、實用功能
新建一個util.js
- ~ vi util.js
- var _ = require("underscore")._;
noConflict: 把 “_” 變量的控制權預留給它原有的所有者. 返回一個引用給 Underscore 對象.
- var underscore = _.noConflict();
identity: 返回與傳入參數相等的值. 相當於數學里的: f(x) = x
- var moe = {name : 'moe'};
- console.log(moe === _.identity(moe));
- => true
times: 設計調用次數
- _(3).times(function(n){ console.log(n); });
- => 0
- 1
- 2
random: 返回范圍內的隨機數
- console.log(_.random(0, 100));
- => 30
mixin: 封裝自己的函數到Underscore對象中,后面Underscore.string就是這種方式的集成
- _.mixin({
- capitalize : function(string) {
- return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
- }
- });
- console.log(_("fabio").capitalize());
- => Fabio
uniqueId:產生一個全局的唯一id,以參數作為前綴
- console.log(_.uniqueId('contact_'));
- => contact_1
- console.log(_.uniqueId('contact_'));
- => contact_2
escape,unescape:轉義HTML字符串,反轉到HTML字符串
- console.log(_.escape('Curly, Larry & Moe'));
- => Curly, Larry & Moe
- console.log(_.unescape('Curly, Larry & Moe'));
- => Curly, Larry & Moe
result: 通過字符串調用對象的函數,或返回屬性值
- var obj = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }};
- console.log(_.result(obj, 'cheese'));
- => crumpets
- console.log(_.result(obj, 'stuff'));
- => nonsense
template: 將 JavaScript 模板編譯為可以用於頁面呈現的函數, 對於通過JSON數據源生成復雜的HTML並呈現出來的操作非常有用. 模板函數可以通過以下兩種方式插入到頁面中, 使用<%= … %>, 也可以用<% … %>執行任意的 JavaScript 代碼. 如果您希望插入一個值, 並讓其進行HTML轉義, 當您使用創建一個模板時使用 <%- … %> , 傳入一個含有與模板對應屬性的對象 data. 如果您要寫一個一次性的, 您可以傳對象 data 作為第二個參數給模板template 來直接呈現, 這樣頁面會立即呈現而不是返回一個模板函數. 參數 settings 是一個哈希表包含任何可以覆蓋的設置 _.templateSettings.
- var compiled = _.template("hello: <%= name %>");
- console.log(compiled({name : 'moe'}));
- =>hello: moe
- var list = "<% _.each(people, function(name) { %> <li><%= name %></li> <% }); %>";
- console.log(_.template(list, {people : ['moe', 'curly', 'larry']}));
- => <li>moe</li> <li>curly</li> <li>larry</li>
- var template = _.template("<b><%- value %></b>");
- console.log(template({value : '<script>'}));
- => <b><script></b>
- var compiled = _.template("<% print('Hello ' + epithet); %>");
- console.log(compiled({epithet: "stooge"}));
- =>Hello stooge
- console.log(_.template("Using 'with': <%= data.answer %>", {answer: 'no'}, {variable: 'data'}));
- =>Using 'with': no
- _.templateSettings = {
- interpolate : /\{\{(.+?)\}\}/g
- };
- var template = _.template("Hello {{ name }}!");
- console.log(template({name : "Mustache"}));
- =>Hello Mustache!
6、鏈式語法
新建一個chaining.js
- ~ vi chaining.js
- var _ = require("underscore")._;
chain: 返回一個封裝的對象. 在封裝的對象上調用方法會返回封裝的對象本身, 直到value() 方法調用為止.
- 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();
- console.log(youngest);
- => moe is 21
對一個對象使用 chain 方法, 會把這個對象封裝並 讓以后每次方法的調用結束后都返回這個封裝的對象, 當您完成了計算, 可以使用 value 函數來取得最終的值. 以下是一個同時使用了 map/flatten/reduce 的鏈式語法例子, 目的是計算一首歌的歌詞里每一個單詞出現的次數.
- 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"}
- ];
- console.log(
- _.chain(lyrics)
- .map(function(line) { return line.words.split(' '); })
- .flatten()
- .reduce(function(counts, word) {
- counts[word] = (counts[word] || 0) + 1;
- return counts;
- }, {})
- .value()
- );
- => { 'I\'m': 2,
- a: 2,
- lumberjack: 2,
- and: 4,
- okay: 2,
- I: 2,
- sleep: 1,
- all: 4,
- night: 2,
- work: 1,
- day: 2,
- 'He\'s': 1,
- 'he\'s': 1,
- He: 1,
- sleeps: 1,
- he: 1,
- works: 1 }
value: 提取封裝對象的最終值,作為chain()結束標志。
- console.log(_([1, 2, 3]).value());
7、字符串處理Underscore.String
安裝underscore.string
- ~ D:\workspace\javascript\nodejs-underscore>npm install underscore.string
- npm http GET https://registry.npmjs.org/underscore.string
- npm http 304 https://registry.npmjs.org/underscore.string
- underscore.string@2.3.3 node_modules\underscore.string
新建一個string.js,通過mixin()函數,讓underscore.string和underscore集成統計實現_.fun()語法。
- ~ vi string.js
- var _ = require('underscore');
- _.str = require('underscore.string');
- _.mixin(_.str.exports());
字符串的數字格式化
- console.log(_.numberFormat(1000, 2));
- => 1,000.00
- console.log(_.numberFormat(123456789.123, 5, '.', ','));
- => 123,456,789.12300
- console.log(_('2.556').toNumber());
- => 3
- console.log(_('2.556').toNumber(2));
- => 2.56
- console.log(_.sprintf("%.1f", 1.17));
- => 1.2
字符串基礎操作
- console.log(_.levenshtein('kitten', 'kittah'));
- => 2
- console.log(_.capitalize('epeli'));
- => Epeli
- console.log(_.chop('whitespace', 3));
- => [ 'whi', 'tes', 'pac', 'e' ]
- console.log(_.clean(" foo bar "));
- => foo bar
- console.log(_.chars('Hello'));
- => [ 'H', 'e', 'l', 'l', 'o' ]
- console.log(_.swapCase('hELLO'));
- => Hello
- console.log(_.str.include("foobar", "ob")); //不兼容API,需要用_.str.fun()
- => true
- console.log(_.str.reverse("foobar"));//不兼容API,需要用_.str.fun()
- => raboof
- console.log(_('Hello world').count('l'));
- => 3
- console.log(_('Hello ').insert(6, 'world'));
- => Hello world
- console.log(_('').isBlank() && _('\n').isBlank() && _(' ').isBlank());
- => true
- console.log(_.join(",", "foo", "bar"));
- => foo,bar
- console.log(_.lines("Hello\nWorld"));
- => [ 'Hello', 'World' ]
- console.log(_("image.gif").startsWith("image"));
- => true
- console.log(_("image.gif").endsWith("gif"));
- => true
- console.log(_('a').succ());//指下編碼的下一個
- => b
字符串變換
- console.log(_.repeat("foo", 3));
- => foofoofoo
- console.log(_.repeat("foo", 3, "bar"));
- => foobarfoobarfoo
- console.log(_.surround("foo", "ab"));
- => abfooab
- console.log(_.quote('foo', "#"));
- => #foo#
- console.log(_.unquote('"foo"'));
- => foo
- console.log(_.unquote("'foo'", "'"));
- => foo
- console.log(_.slugify("Un éléphant à l'orée du bois"));
- => un-elephant-a-loree-du-bois
- console.log(['foo20', 'foo5'].sort(_.naturalCmp));
- => [ 'foo5', 'foo20' ]
- console.log(_.toBoolean("true"));
- => true
- console.log(_.toBoolean("truthy", ["truthy"], ["falsy"]));
- => true
- console.log(_.toBoolean("true only at start", [/^true/]));
- => true
字符串替換,截斷
- console.log(_('https://edtsech@bitbucket.org/edtsech/underscore.strings').splice(30, 7, 'epeli'));
- => https://edtsech@bitbucket.org/epeli/underscore.strings
- console.log(_.trim(" foobar "));
- => foobar
- console.log(_.trim("_-foobar-_", "_-"));
- => foobar
- console.log(_('Hello world').truncate(5));
- => Hello...
- console.log(_('Hello, world').prune(5));
- => Hello...
- console.log(_('Hello, world').prune(5, ' (read a lot more)'));
- => Hello, world
- console.log(_.words(" I love you "));
- => [ 'I', 'love', 'you' ]
- console.log(_.words("I-love-you", /-/));
- => [ 'I', 'love', 'you' ]
- console.log(_('This_is_a_test_string').strRight('_'));
- => is_a_test_string
- console.log(_('This_is_a_test_string').strRightBack('_'));
- => string
- console.log(_('This_is_a_test_string').strLeft('_'));
- => This
- console.log(_('This_is_a_test_string').strLeftBack('_'));
- => This_is_a_test
字符串占位
- console.log(_.pad("1", 8));
- => 1
- console.log(_.pad("1", 8, '0'));
- => 00000001
- console.log(_.pad("1", 8, '0', 'right'));
- => 10000000
- console.log(_.pad("1", 8, 'bleepblorp', 'both'));
- => bbbb1bbb
- console.log(_.lpad("1", 8, '0'));
- => 00000001
- console.log(_.rpad("1", 8, '0'));
- => 10000000
- console.log(_.lrpad("1", 8, '0'));
- => 00001000
字符串語義處理
- console.log(_.toSentence(['jQuery', 'Mootools', 'Prototype']));
- => jQuery, Mootools and Prototype
- console.log(_.toSentence(['jQuery', 'Mootools', 'Prototype'], ', ', ' unt '));
- => jQuery, Mootools unt Prototype
- console.log(_.toSentenceSerial(['jQuery', 'Mootools']));
- => jQuery and Mootools
- console.log(_.toSentenceSerial(['jQuery', 'Mootools', 'Prototype']));
- => jQuery, Mootools, and Prototype
- console.log(_('my name is epeli').titleize());
- => My Name Is Epeli
- console.log(_('-moz-transform').camelize());
- => MozTransform
- console.log(_('some_class_name').classify());
- => SomeClassName
- console.log(_('MozTransform').underscored());
- => moz_transform
- console.log(_('MozTransform').dasherize());
- => -moz-transform
- console.log(_(' capitalize dash-CamelCase_underscore trim ').humanize());
- => Capitalize dash camel case underscore trim
HTML相關操作
- console.log(_('<div>Blah blah blah</div>').escapeHTML());
- => <div>Blah blah blah</div>
- console.log(_('<div>Blah blah blah</div>').unescapeHTML());
- =><div>Blah blah blah</div>
- console.log(_('a <a href="#">link</a>').stripTags());
- =>a link
- console.log(_('a <a href="#">link</a><script>alert("hello world!")</script>').stripTags());
- =>a linkalert("hello world!")
三、underscore.string.js
version: underscore.string 3.2.1 | MIT licensed | http://epeli.github.com/underscore.string/
- <script src="underscore.js"></script>
- <script src="underscore.string.js"></script>
- <script type="text/javascript">
- console.log(s.exports());
- _.mixin(s.exports());
- alert(_.capitalize("sdfds"));
- </script>
或者
- <script src="underscore.string.js"></script>
- <script type="text/javascript">
- console.log(s.capitalize("fuckit"));
- </script>
說明underscore.string.js可以獨立於underscore.js存在,會暴露出s全局變量。
轉自 http://blog.csdn.net/qhairen/article/details/49447787