function map(ls,func){
var d=[];
for(var i=0;i d.push(func.call(this,ls[i]))
}
return d;
}
map([1,2,3],function(n){return n+1})
[2, 3, 4]
function select(ls,func){
var d=[];
for(var i=0;i if(func.call(this,ls[i]))
d.push(ls[i])
}
return d;
}
select([1,2,3],function(n){return n%2==0;})
2
function reject(ls,func){
var d=[];
for(var i=0;i if(!func.call(this,ls[i])){d.push(ls[i])}
}
return d;
}
reject([1,2,3,4,5,6],function(n){ return n%2==0})
function any(ls,func){
for(var i=0;i if(func.call(this,ls[i]))
return true
}
return false;
}
function truth(n){ if(n){return true}else{return false}}
any([1,0,1],truth)
true
function all(ls,func){
for(var i=0;i if(!func.call(this,ls[i]))
return false;
}
return true;
}
function truth(n){ if(n){return true}else{return false}}
all([1,0,1],truth)
function max(ls,func){
var d = ls.sort(func);console.log(d); return d[0];
}
max([1,2,3,4,5,6],function(s1,s2){ if(s1.age <= s2.age){return -1}else{return 1} })
function min(ls,func){
var d = ls.sort(func);console.log(d); return d[0];
}
min([1,2,3,4,5,6],function(s1,s2){ if(s1.age > s2.age){return -1}else{return 1} })
function uniq(ls){
var d =[];var r=[];
for(var i=0;i for(var field in d){r.push(d[field])};
return r;
}
uniq([1,2,3,4,5,6,1])
[1, 2, 3, 4, 5, 6]
function range(start,end,step)
{
if(arguments.length==1){end=start;start=1;step=1;}
if(!step){step=1};
var r=[];
for(var i=start;i<=end;i=i+step){r.push(i)} return r;
}
range(10)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
range(2,10)
[2, 3, 4, 5, 6, 7, 8, 9, 10]
function fib(n){ return n<2 ? n : arguments.callee(n-1) + arguments.callee(n-2) }
function delay(func,time,args){console.log(args);
setTimeout(function(args){
return ( function(){func.apply(this,args)} )()}
,time)};
delay(function(n){alert("yes "+n)},1000,10);
bind = function(func, obj) {
return function() {
return func.apply(obj, arguments);
};
};
当然之前写的rails 风格的代码以及有人实现,名叫 Underscore.js,
感兴趣的人可以看看
[url]http://documentcloud.github.com/underscore[/url]
其中有几个经典的用法
var fibonacci = function(n) {
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
};
var fastFibonacci = _.memoize(fibonacci);
_.mixin({
capitalize : function(string) {
return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
}
});
_("fabio").capitalize();
=> "Fabio"
var compiled = _.template("hello: <%= name %>");
compiled({name : 'moe'});
=> "hello: moe"
var list = "<% _.each(people, function(name) { %> <%= name %> <% }); %>";
_.template(list, {people : ['moe', 'curly', 'larry']});
=> "moecurlylarry"