首页 > 代码库 > Underscore.js基础入门

Underscore.js基础入门

公司产品集成了对Underscore.js,所以需要对这个库有一定的了解。通过查阅资料,发现这个库主是对Array和JSON的处理支持。通过Underscore.js库,可以方便的对Array和JSON数据进行操作。下面是一些我学习中做测试写的示例,po在这里,供将来复习。

var $ = lib.c.$;var _ = lib.Underscore.require();/*这个函数演示了map的使用方法map接受JSON和Arraymap函数第一个参数是一个Array/JSON(object)类型的数据,第二个参数是一个处理函数返回值是一个数组*/function mapDemo(){    var personInfo =     {        name:"sheldon",        age:28,        gender:"male",        cellNumber:"15527738495"    };    var result = _.map(personInfo,function(value, key)    {        return value;    });    print(result);    print(result[2]);        print("=================");        var numberArray = [1,3,2,1,2,3];    result = _.map(numberArray,function(item)    {        return item * item;    });        print(result);    print(result[2]); }function everyAndSomeDemo(){    var numberArray = [1,3,2,1,2,3];    var result = _.every(numberArray,function(item)    {        return item > 2;    });    print("所有的元素都大于2: " + result);        result = _.some(numberArray,function(item)    {        return item > 2;    });    print("部分元素都大于2: " + result);            var boxInfo = {height:true,width:false,length:true};    result = _.every(boxInfo,function(val,key)    {        return val == true;    });        print("箱子的所有指标(长/宽/高)都正确: " + result);    result = _.some(boxInfo,function(val,key)    {        return val == true;    });        print("箱子的部分指标(长/宽/高)正确: " + result);}function maxDemo(){    var numberArray = [1,3,2,1,2,3];    var maxNumber = _.max(numberArray);    print("max number in array:" + maxNumber);        //NOTE: the key should not be length. otherwise the result is infinity    var numberObject = {"height":133,"width":146,"length":122};    maxNumber = _.max(numberObject);    print("max number in JSON(object):" + maxNumber);        var numberObject1 = {"height":133,"width":146,"length1":122};    maxNumber = _.max(numberObject1);    print("max number in JSON(object):" + maxNumber);}function groupByDemo(){    var scoresInArray = [20, 81, 75, 40, 91, 59, 77, 66, 72, 88, 99];    var result = _.groupBy(scoresInArray,function(item)    {        if(item < 60 )            return "不及格";        else if(item >= 60 && item < 80)            return "合格";        else            return "优秀";    });    for(var key in result)    {        print(key + ":" + result[key]);    }        var scoresInObject =     {        "小明":22,        "小张":67,        "小红":45,        "小华":99,        "小贾":85    };        //对object进行分组的时候,只对value进行分组    result = _.groupBy(scoresInObject,function(value)    {        if(value < 60 )            return "不及格";        else if(value >= 60 && value < 80)            return "合格";        else            return "优秀";    });        for(var key in result)    {        print(key + ":" + result[key]);    }    }//用洗牌算法随机打乱一个集合:function shuffleDemo(){    // 注意每次结果都不一样:    var result = _.shuffle([1, 2, 3, 4, 5, 6]); // [3, 5, 4, 6, 2, 1]    print(result);}//随机选择一个或多个元素:function sampleDemo(){    // 注意每次结果都不一样:    // 随机选1个:    var result = _.sample([1, 2, 3, 4, 5, 6]); // 2    print(result);    // 随机选3个:    result = _.sample([1, 2, 3, 4, 5, 6], 3); // [6, 1, 4]    print(result);} //keys()可以非常方便地返回一个object自身所有的key,但不包含从原型链继承下来的:function keysDemo(){    function Student(name,age)    {        this.name = name;        this.age = age;    }        var xm = new Student("xiaoming",23);     var keysXM = _.keys(xm);// [‘name‘, ‘age‘]        for(var index in keysXM)    {        var key = keysXM[index];         print(key + ":" + xm[key]);    }}//和keys()类似,values()返回object自身但不包含原型链继承的所有值:function valuesDemo(){    function Student(name,age)    {        this.name = name;        this.age = age;    }        var xm = new Student("xiaoming",23);     var valuesXM = _.values(xm);// [‘小明‘, 20]    for(var index in valuesXM)    {        print(valuesXM[index]);    }}//invert()把object的每个key-value来个交换,key变成value,value变成key:function invertDemo(){    function Scores(math,english,computer)    {        this.math = math;        this.english = english;        this.computer = computer;    }        var testResult = new Scores(66,75,94);    var testResultInverted = _.invert(testResult);    var keysOfTestResult = _.keys(testResult);    var keysOfTestResultInverted = _.keys(testResultInverted);        for(var index in keysOfTestResult)    {        var key = keysOfTestResult[index];        print(key + ":" + testResult[key]);    }    print("===============");        for(var index in keysOfTestResultInverted)    {        var key = keysOfTestResultInverted[index];        print(key + ":" + testResultInverted[key]);    }}//如果我们要复制一个object对象,就可以用clone()方法,它会把原有对象的所有属性都复制到新的对象中:function cloneDemo(){    var source =     {        name: ‘小明‘,        age: 20,        skills: [‘JavaScript‘, ‘CSS‘, ‘HTML‘]    };        var copied = _.clone(source);    print(copied == source);    print(copied.name == source.name);    print(copied.age == source.age);    //注意,clone()是“浅复制”。所谓“浅复制”就是说,两个对象相同的key所引用的value其实是同一对象:    print(copied.skills == source.skills);}//isEqual()对两个object进行深度比较,如果内容完全相同,则返回true//isEqual()对两个object进行深度比较,如果内容完全相同,则返回truefunction isEqualDemo(){    var o1 = { name: ‘Bob‘, skills: { Java: 90, JavaScript: 99 }};    var o2 = { name: ‘Bob‘, skills: { JavaScript: 99, Java: 90 }};        print(o1 === o2); // false    print(_.isEqual(o1, o2)); // true        //isEqual()其实对Array也可以比较    o1 = [‘Bob‘, { skills: [‘Java‘, ‘JavaScript‘] }];    o2 = [‘Bob‘, { skills: [‘Java‘, ‘JavaScript‘] }];        print(o1 === o2); // false    print(_.isEqual(o1, o2)); // true}function chainDemo(){    var numberArray = [1,3,2,1,2,3,2,7,7,8,2];    var result = _.chain(numberArray).filter(function(item)    {        return item%2 == 0;    }).map(function (item)    {        return item*2;    }).value();        print(result);}

 

Underscore.js基础入门