(AS3)操作数组的每个元素:forEach,every,filter,map,some

 1 package
 2 {
 3     import flash.display.Sprite;
 4     
 5     public class ArrayforEeach_etc extends Sprite
 6     {
 7         var book1:Object={name:"actionscript 3 殿堂之路",author:"kingda"};
 8         
 9         var book2:Object={name:"flex 3 殿堂之路",author:"kingda"};
10         var book3:Object={name:"flash 3 殿堂之路",author:"kingda"};
11         var book4:Object={name:"大话设计模式",author:"ll"};
12         var bookList:Array=[book1,book2,book3,book4];
13         
14         public function ArrayforEeach_etc()
15         {
16             trace("这套书没有过时的书?"+bookList.every(noflash));//every,返回是否每个对象都满足使noflash为true的条件
17             var newbookList:Array=bookList.map(mapNewList);//map,根据回调函数操作员数组的每个元素并利用回调函数返回的结果生成新的数组。
18             trace("新书单:"+newbookList[2].price);
19             trace("有kingda的书吗?"+bookList.some(isKingda));//只要有一个元素能让回调函数返回true,则some()返回true,否则false
20             var newbookList2:Array=bookList.filter(noKingda);//将符合回调函数条件的元素提取出来,构成一个新的数组并返回
21             trace("不是kingda的书:"+newbookList2[0].name);
22             bookList.forEach(showName);//为每个元素调用回调函数
23         }
24         
25         function noflash(item:Object,index:int,arr:Array):Boolean
26         {
27             if(item.name.indexOf("flash")!=-1)
28             {
29                 trace("第"+(index+1)+"本过时了");
30                 return false;
31             }
32             return true;
33         }
34         
35         function mapNewList(item:Object,index:int,arr:Array):Object
36         {
37             var newbook:Object=new Object();
38             newbook.name=item.name;
39             newbook.author=item.name;
40             newbook.price=1000;
41             return newbook;
42         }
43         
44         function isKingda(item:Object,index:int,arr:Array):Boolean
45         {
46             if(item.author=="kingda")
47                 return true;
48             return false;
49         }
50         
51         function noKingda(item:Object,index:int,arr:Array):Boolean
52         {
53             if(item.author!="kingda")
54                 return true;
55             return false;
56         }
57         
58         
59         function showName(item:Object,index:int,arr:Array):void
60         {
61             trace(item.name);
62         }
63     }
64 }

 结果:

posted @ 2012-07-18 17:11  ☆A希亿  阅读(3984)  评论(0编辑  收藏  举报