1、理清概念
一、Underscore封裝了經常使用的JavaScript對象操做方法,用於提升開發效率,Underscore還能夠被使用在Node.js運行環境。從API中,你已經能夠看出,Underscore沒有任何複雜的結構和流程,它僅僅提供了一系列經常使用的函數。若是你將API中的方法從頭到尾用一遍,你就會對它很是瞭解。
二、Underscore並無在原生的JavaScript對象原型中進行擴展,而是像jQuery同樣,將數據封裝在一個自定義對象中(下文中稱「Underscore對象」)。能夠經過調用一個Underscore對象的value()方法來獲取原生的javascript數據。javascript
三、Underscore.js是一個很精幹的庫,壓縮後只有4KB。它提供了幾十種函數式編程的方法,彌補了標準庫的不足,大大方便了JavaScript的編程。MVC框架Backbone.js就將這個庫做爲本身的工具庫。除了能夠在瀏覽器環境使用,Underscore.js還能夠用於Node.js。Underscor.js定義了一個下劃線(_)對象,函數庫的全部方法都屬於這個對象。這些方法大體上能夠分紅:集合(collection)、數組(array)、函數(function)、對象(object)和工具(utility)五大類。java
2、經常使用庫函數node
一、 集合部分: 數組或對象
Javascript語言的數據集合,包括兩種結構:數組和對象。如下的方法同時適用於這兩種結構。
新建一個collection.js文件,測試underscore對集合的支持。jquery
- ~ vi collection.js
-
- //加載underscore庫
- var _ = require("underscore")._;
each: 對集合循環操做git
- _.each([1, 2, 3], function (ele, idx) {
- console.log(idx + ":" + ele);
- });
- => 0:1
- 1:2
- 2:3
map: 對集合以map方式遍歷,產生一個新數組github
- 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:只返回第一個npm
- 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, 返回新的對象數組api
- 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})
- );
二、數組部分
新建一個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 }
三、函數部分
新建一個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!
四、對象部分
新建一個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
五、實用功能
新建一個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!
六、鏈式語法
新建一個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());
七、字符串處理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!")
3、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