js filter的使用

Person 类:
/*
person class
*/
function Person(name,age){
this.name = name;
this.age = age;
this.hobby = new Array();
}

Person.prototype ={

/*
name prop
*/
getName : function(){
return this.name;
},

setName : function(name){
this.name = name;
},

showName : function(){
alert(this.name);
},

/*
age prop
*/
getAge : function(){
return this.age;
},

setAge : function(age){
this.age = age;
},


/*
hobby prop
*/
addHobby: function(key,value){
this.hobby[key] = value;
},

showHobby: function(){
var hobbyStr = "";
for(var h in this.hobby){
hobbyStr += h + "\r\n";
}
alert(hobbyStr);
}



}

/*
extend class(dynamic)
*/
Person.prototype.getGreeting = function(){
return "hello," + this.name;
}



使用Filter示例:

/////初始化100个人
var persons = new Array();
for(var i = 0;i<100;i ++){
persons.push(new Person("person" + i.toString(),i));
}

////找出年龄小于20岁的人,非常方便,类似lambda表达式了
var youngerGuys = persons.filter(function(p){return p.getAge() < 20;});

var ret = "";
for(var i = 0;i <youngerGuys.length;i ++){
ret += youngerGuys[i].getName() + " \r\n";
}
alert(ret);


/*
EVERY 和 SOME的用法
*/

////false
var allPersonIsOldMan = persons.every(function(p){return p.getAge()>50;});
alert(allPersonIsOldMan);

////true
var someoneIsOldMan = persons.some(function(p){return p.getAge() > 50;});
alert(someoneIsOldMan);

/*
MAP用法
*/

var allPerson = persons.map(function(p){p.setName(p.getName() + "map");return p;});
PrintRet(allPerson);


你可能感兴趣的:(function,filter,Class,lambda)