underscore api 概览

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]);//生成全局唯一id

  • _.escape(str); //转义 &, <, >, " ,', /

  • _.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>&lt;script&gt;</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
  • _.chain(obj);//链式语法
    //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(); //返回封装对象的最终值
原文地址:https://www.cnblogs.com/stephenykk/p/5033472.html