一直想為js寫一個數組排序,遍歷,字符串操作的綜合的大類,不知道盡然有Underscore這么好的東西。
Underscore是與backnone一起的方法庫。來見識一下underscore的強大吧。
_each :_.each(list, iterator, [context])
list 為數組時 iterator傳遞三個參數(element, index, list)
list為對象時 iterator傳遞三個參數(value, key, list)
如果傳遞了context參數,則把iterator綁定到context對象上。
var someOtherArray = ["name","patrick","d","w"]; _.each([1, 2, 3], function(num) { // In here, "this" refers to the same Array as "someOtherArray" alert( this[num] ); // num is the value from the array being iterated // so this[num] gets the item at the "num" index of // someOtherArray. }, someOtherArray);
var person = {}; person.friends = { name1: "kitty", name2: "sonny", name3: "age", name4: "ponny" }; _.each(['name4', 'name2'], function(name){ // this refers to the friends object op person alert(name+":"+this[name]); }, person.friends);
這樣當遍歷一個數據集合只需或個別屬性的值,不需要通過if else這樣繁瑣的判斷,對比jquery的$.each()多了context參數。不能代替$(obj).each().
sortby:uderscore輕松完成多維數組單個字段的(時間,數字,字符)排序
(function ($) { var arry=[{name:"kityy",age:21}, {name:"sonny",age:3 }, { name:"bage",age:29}, {name:"quick",age:33 }, { name:"funny",age:35 }] var sorted= _.sortBy(arry,function(data){ return -data.age}) for(var i = 0; i < sorted.length; ++i) console.log(sorted[i]["name"]+":"+sorted[i]["age"]); })(jQuery);
在backbone中使用:
M = Backbone.Model.extend(); C = Backbone.Collection.extend({ model: M }); var c = new C(); c.add([ {name:"kityy",age:21}, {name:"sonny",age:3 }, { name:"bage",age:29}, {name:"quick",age:33 }, { name:"funny",age:35 } ]); var sorted = c.sortBy(function(m) { return -m.get('age')}); for(var i = 0; i < sorted.length; ++i) console.log(sorted[i].get('name')+":"+sorted[i].get('age'));
flatten_.flatten(array)
將多維數組合並成一位數組,js里用處不大
extend: underscore 合並對象,翻譯成update對象更形象,backbone依賴這個方法做做原型鏈的擴展
var ArrayProto = Array.prototype, slice = ArrayProto.slice var extend = function (obj) { _.each(slice.call(arguments, 1), function (source) { if (source) { for (var prop in source) { obj[prop] = source[prop]; } } }); return obj; };
使用方法
extend(hh,{o:21},{mm:45})