一直想为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})
