借助ES6 generator,写了一个小型迭代数组的库,可以像下面这样使用
//取1到10中的偶数,然后取这些偶数的平方
var _1to10 = [1,2,3,4,5,6,7,8,9,10];
var arr =iter(_1to10)
.where(function(v){return v%2==0})
.map(function(v){return v*v})
.toArray();
console.log(arr); // [4, 16, 36, 64, 100]
//对年龄大于20的人,按年龄进行排序
var person = [{first:'god',last:'pig',age:25,male:'m'},
{first:'wang',last:'er',age:26,male:'m'},
{first:'zhang',last:'san',age:18,male:'m'},
{first:'li',last:'si',age:19,male:'m'},
{first:'god',last:'pig',age:21,male:'m'},
{first:'god',last:'cat',age:22,male:'m'}];
var arr= iter(person)
.where(function(v){return v.age>20})
.sort(function(v1,v2){return v1.age-v2.age})
.toArray();
//arr:[{..age:21..} , ... , {..age:26}...]
我个人觉得这种用法很有吸引力,特别是加上lambda表达式后。https://github.com/jzlxiaohei/yield-iter上有更多demo,请大家拍砖