---
title: "关于“数据分页”"
author: "wgcode"
date: "2010-12-25T14:00:19Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-12-25T14:00:19Z"
id: 851719
url: "https://tts.iteye.com/blog/851719"
---

分页是游戏和应用程序开发中经常需要用到的一个程序，  
在游戏开发中我用得最多的算是数组(ArrayPages)分页和哈希表(HashMapPages)分页。  
比如《抢车位》游戏中的“场景店”模块、《QQ农场》中的好友列表、常见新闻列表分页等等。

下面我提供之前写的ArrayPages.as ,哈希表的分页就类似。

AS3代码

01. package com.lbynet.util
02. {
03. /\**
04. * ...
05. * @author lbynet (Tools -&gt; 数组数据分页...)
06. * @version 0.2
07. * @copy shch8.com All Rights Reserved At 2008
08. \*/
09. public class ArrayPages
10. {
11. private var data\_array:Array; // 存储所有数据
12. private var pageRecord:int;// 每页的数据个数
13. private var arrayLength:int;// 总个数
14. public var totalPages:int; // 总页数
15. public function ArrayPages(\_data:Array, \_pagerecord:int = 4)
16. {
17. if (\_data != null)
18. {
19. this.data\_array = \_data;
20. this.pageRecord = \_pagerecord;
21. this.arrayLength = this.data\_array.length;
22. this.totalPages = this.arrayLength / this.pageRecord;
23. if (this.arrayLength % this.pageRecord &gt; 0)
24. {
25. this.totalPages += 1;
26. }
27. }
28. //trace(this.data\_array);
29. //trace(this.pageRecord);
30. //trace(this.arrayLength);
31. //trace(this.totalPages);
32. }
33. /* 取出某一页的数据 (1-totalPages) \*/
34. public function getPageData(curpage:uint):Array
35. {
36. if (curpage &lt;= 0||curpage &gt; this.totalPages)
37. {
38. throw new Error('页数必需在 1 - ' + this.totalPages + ' 页 以内');
39. }
40. var \_startIndex:int;// 某页的第一条数据
41. if (curpage == 1)
42. {
43. \_startIndex = 0;
44. }
45. else
46. {
47. \_startIndex = (curpage - 1) * pageRecord;
48. }
49. var \_endIndex:int = \_startIndex + pageRecord; // 某页的最后一条数据
50. if (curpage &gt;= this.totalPages && \_endIndex != this.arrayLength)// (\_endIndex != this.arrayLength)  === (this.arrayLength % this.pageRecord == 0)
51. {
52. \_endIndex = \_startIndex + this.arrayLength % this.pageRecord;
53. }
54. //trace('                           ', \_startIndex, \_endIndex);
55. return data\_array.slice(\_startIndex, \_endIndex);
56. }
57. }
58. }