underscore
集合函數(數組或對象)
- _.each(list, iteratee, [context]);
- _.map(list, iteratee, [context]);
- _.reduce(list, iteratee, [memo], [context]); //foldl
- _.reduceRight(list, iteratee, [memo], [context]); //foldr
- _.find(list, predicate, [context]); //detect
- _.filter(list, predicate, [context]); //select
- _.where(list, properties);//返回對象數組,每一個對象包含指定的properties
- _.findWhere(list, properties);
- _.reject(list, predicate, [context]); //與filter相反
- _.every(list, [predicate], [context]); //all
- _.some(list, [predicate], [context]); //any
- _.contains(list, value); //include
- _.invoke(list, methodName, *arguments);
- _.pluck(list, propertyName);
- _.max(list, iteratee, [context]);
- _.min(list, iteratee, [context]);
- _.sortBy(list, iteratee, [context]);
- _.groupBy(list, iteratee, [context]); //=> return obj
- _.indexBy(list, iteratee, [context]); //=> return obj
- _.countBy(list, iteratee, [context]); //=> return obj
- _.shuffle(list);
- _.sample(list,[n]);
- _.toArray(list); // like $.makeArray
- _.size(list);
- _.partition(list, predicate);//數組分紅2個子數組 爲true, 爲false
數組函數
- _.first(array, [n]); //默認 n=1
- _.initial(array, [n]); //從末尾刪除n個元素後的子數組 默認n=1
- _.last(array, [n]); //保留最後n個元素,造成的新數組
- .rest(array, [n]);//去掉前面n個元素,造成新的數組 .tail(), _.drop();
- _.compact(array); //刪除全部false值後的數組副本
- _.flatten(array, [shallow]);//扁平化數組 shallow=true則只扁平1層
- _.without(array, *values); //返回刪除values值後的數組副本_
- _.union(*arrays);//數組合並 會去掉重複項
- _.intersection(*arrays); //數組的交集
- _.difference(array, *others); //在源數組中有,其餘數組沒有的元素組成新數組
- .uniq(array); //.unique(array); 數組去重
- _.zip(*arrays); //每一個數組相應位置的值合併在一塊兒,返回二維數組
- _.object(list, [values]); //兩個數組轉換爲對象,或二維數組轉換爲對象[['name1','val1'],['name2', 'val2']]
- _.indexOf(array, value, [isSorted]);
- _.lastIndexOf(array, value, [fromIndex]);
- _.sortedIndex(list, value, [iteratee], [context]); //返回value在list中的位置序號
- _.range([start], stop, [step]); //返回整數數組
函數相關的函數
- _.bind(function, object, *arguments); //綁定上下文 和 部分參數 返回偏函數
var func = function(greeting){ return greeting + ': ' + this.name; };
func = _.bind(func, {name:'sindy'}, 'hi');
func();
- _.bindAll(object, *methodNames);
var buttonView = {
label: 'underscore',
onClick: function(){ alert('clicked ' + this.label); },
onHover: function(){ console.log('hovering ' + this.label); }
};
_.bindAll(buttonView, 'onClick', 'onHover');
$('#underscoreBtn').bind('click', buttonView.onClick);
- _.partial(function, *arguments); //相似bind,只是不綁定上下文對象, 返回偏函數
var add = function(a, b){ return a+b; };
var add5 = _.partial(add, 5);
add5(10); //15
- _.memoize(function, [hashFunction]); //緩存某函數的計算結果
var fibonacci = _.memoize(function(n){
return n<2?n:fibonacci(n-1) + fibonacci(n-2);
});
- _.delay(function, wait, *arguments); //相似setTimeout, 可是能夠傳遞參數給回調函數
var log = _.bind(console.log, console);
_.delay(log, 1000, 'logged later');
- _.defer(function, *arguments);//延遲調用函數直到調用棧爲空, 相似setTimeout(function, 0); 只是可傳入參數
_.defer(alert, 'some deferred tips');
- _.throttle(function, wait, [options]); //限制執行頻率
var throttled = _.throttle(updatePosition, 100);
$(window).scroll(throttled);
- _.debounce(function, wait, [immediate]);//將函數的執行真正延遲到最後一次調用的wait秒以後
var lazyLayout = _.debounce(calculateLayout, 300);
$(window).resize(lazyLayout);
- _.once(function); //建立一個只能調用一次的函數,重複調用,只會返回第一次調用的結果
var init = _.once(createApplication);
init();
init();
- _.after(count, function); 只有在執行了count次以後,才真正執行function
var renderNotes = _.after(notes.length, render);
_.each(notes, function(){
note.asyncSave({success: renderNotes});
});// renderNotes is run once, after all notes have saved
- _.before(count, function); //count次以前正常執行函數,count次以及其後的調用返回最後一次調用的結果
var monthlyMeeting = _.before(3, raise);
monthlyMeeting();
monthlyMeeting();
- _.wrap(function, wrapper); //裝飾者模式..
var hello = function(name){ return 'hello ' + name; };
hello = _.wrap(hello, function(func){
return 'before ' + func('moe') + ' after';
};
hello();
- _.negate(predicate); //返回predicate函數的否認版本
var isFalsy = _.negate(Boolean);
_.find([1,2,0,33,11], isFalsy); //0
- _.compose(*functions); //返回函數集組合後的複合函數
// _.compose(f,g,h); => h(g(f()))
var greet = function(name){ return 'hello ' + name; };
var exclaim = function(statement){ return statement.toUpperCase() + '!';};
var welcome = _.compose(greet, exclaim);
welcome('sindy');
對象相關函數
- _.keys(object); //返回key組成的數組
- _.values(object); //返回value組成的數組
- _.pairs(object); //對象轉換爲[[key1,val1],[key2, val2]]這樣的二維數組
- _.invert(object); //返回key-value對調後的對象
var obj = {'one':1, 'two': 2 , 'three':3};
_.invert(obj);
- .functions(object); //返回對象裏全部的方法名組成的數組 .methods()
- _.extend(dest, *objects);
- _.pick(object, *keys); //_.pick(object, predicate);
- _.omit(object, *keys); //_.omit(object, predicate); //返回從object刪除一些屬性後的副本 和pick相反
- _.defaults(object, *defaults);//用defaults對象填充object對象中的undefined屬性,有點非覆蓋版的extend的感受
var student = {name:'coco', grade:'one'};
_.defaults(student, {grade:'two', teach: 'sisi'});
//=>{name:'coco', teach:'sisi', grade:'one'}
- _.clone(object); //建立一個淺拷貝的對象
- _.tap(object, interceptor); //用object做爲參數調用攔截器函數,而後返回object,以便鏈式調用
_.tap(sindy, function(sindy){ console.log(sindy.name + ' say hi');});
//=> return sindy
- _.has(object, key); //like object.hasOwnProperty(key)
- _.property(key);//返回一個函數,接受一個對象參數,返回該對象key對應的值
var sindy = {name:'sindy', age: 18, major:'singer'};
var getName = _.property('name');
var val = getName(sindy);
- _.matches(attrs); //返回一個斷言函數,判斷入參的對象是否知足 attrs
var matcher = _.matches({major:'singer'});
matcher(sindy); //=> true
- _.isEqual(object1, object2);//按值深度比較兩個對象
- _.isEmpty(object); //object是否爲空(即: 不包含任何可枚舉的屬性)
- _.isElement(object); //是否dom元素
- _.isArray(param);
- _.isObject(val);//是否對象 數組和對象都爲true
- _.isArguments(object); //是否參數對象
(function(){ return _.isArguments(arguments);})(1,2,3);
//=>return true;
- _.isFunction(object); //是否函數
- _.isString(object); //是否字符串
- _.isFinite(val); //是否有限數字
- _.isBoolean(val); //是否邏輯值
- _.isDate(val); //是否日期
- _.isRegExp(val); //是否正則對象
- _.isNaN(val);
- _.isNull(val);
- _.isUndefined(val);
功能函數(utility functions)
- .noConflict(); //讓出變量名"",避免命名空間衝突
var underscore = _.noConflict();
- _.identity(value); //返回與傳入參數相等的值 用做默認的迭代函數
var moe = {name:'moe'};
_.identity(moe); //=> {name: 'moe'}
- _.constant(value); //建立老是返回入參值的函數
var moe = {name: 'moe'};
moe === _.constant(moe)(); //=>true
- _.noop(); //什麼都不作 用做默認的回調函數
- _.times(n, iteratee, [context]);//調用迭代函數n次 返回函數返回值的數組
var grow = function(){ this.age += 1; return this.age; }
var arr = _.times(10, grow, sindy);
- _.random(min, [max]); //返回兩個值之間的隨機整數
- _.mixin(object); //{name:fn, name2: fn2}用相似的函數集擴展underscore,並可用面向對象的方式調用
_.mixin({
capitalize: function(str){
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
});
_('sindy').capitalize(); //Sindy
- _.iteratee(val, [context], [argCount]);//重要的內部函數,返回可應用到集合中每一個元素的回調
var roles = [{name:'alice', age: 18}, {name: 'walmei', age:20}];
_.map(roles, iteratee('age'));
_.uniqueId([prefix]);//生成全局惟一idhtml
_.escape(str); //轉義 &, <, >, " ,', /api
- _.unescape(str); //取消轉義
- _.result(object, property); //若object.property是函數則返回函數執行結果,不然直接返回object.property
_.now(); //返回當前時間戳數組
- _.template(templateString, [setting]); //返回模板函數,等待數據填充
//template語法: <%= ... %>插入變量, <%- ... %>插入作html轉義後的變量
//<% ... %>中間能夠包含js代碼(用 print(str) 來輸出)
var compiled = _.template('hello: <%= name %>');
compiled({name:'sidy'}); //=> 'hello sindy'
var template = _.template('<b><%- value %></b>');
template({value: '<script>'});//=>'<b><script></b>'
var compiled = _.template('<% print("hello " + name); %>');
compiled({name:'sinner'}); //=>'hello sinner'
//用interpolate參數修改默認定界符
_.templateSettings = { interpolate: /\{\{(.+?)\}\}/g };
var template = _.template("hello {{name}}");
template({name: 'wendy'});//=> hello wendy
//underscore提供了函數風格語法和麪向對象語法,可選擇使用,如:
_.map([1,2,3], function(n){ return n*2; }); //下面等價
_([1,2,3]).map(function(n){ return n*2; });
//_.chain(object); chain方法會把對象封裝,讓後續方法都返回封裝後的對象,最好經過.value()方法取出實際的值。
//如: 取出歌詞中每一個單詞出現的次數
var lyrics = [
{line:1, words: "i am a lumberjack and i am okay"},
{line:2, words: "He is a lumberjack and he is okey"},
{line:3, words: "He sleeps all night and 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;
},{});
- _(object).value(); //返回封裝對象的最終值