作者:阿里西西  文章来源:http://www.alixixi.com/  更新时间:2005-12-18
AS基础精典教程 第九章 数组(arrays)

在下一个新版本的多选题里,我们将使用什么AS的特性,来让它更好呢?
那就是数组。
数组就是一系列的数据(MOOCK又开始上课了,chocobo的英文和计算机都不算好,为免误人子弟,概念性的东西尽量精简)
例如这样两个变量储存的数据:
fruit1   =   "oranges";
fruit2   =   "apples";   
它们是互相独立的,使用起来很不方便,我们需要的是数组,以下是数组的定义方法,用“&#;”框住,用“,”分隔开每个元素:
fruitList   =   ["oranges",   "apples"];   
现在两个数据是放到同一个数组里面了,我们开始详细解说数组
数组里面每一个数据称为元素(element)。
而每一个元素都有个独立数字代表所处的位置,数字叫索引(index),注意!   第一个数据的索引是0,第二个才是1
要按索引来提出数据,我们要用一个运算符&#;,例如使用fruitList第一个元素赋值给a:
a=fruitList�;
又例如将a的值赋给fruitList第一个元素:
fruitList�=a;   
当然&#;里面也可以放表达式、变量:
var   index   =   3;
//   Set   numApples   to   2
var   a   =   fruitList[index];   
下面是个使用表达式的例子:
//   Create   a   myFrames   array.   Note   the   legal   formatting.   建立一个记录LABEL的数组
var   myFrames   =   ["storyEnding1",
"storyEnding2",
"storyEnding3",
"storyEnding4"];   
//   Set   randomFrame   to   a   randomly   picked   element   of   myFrames
//   by   calculating   a   random   number   between   0   and   3
//   随机从数组中提取一个LABEL
var   randomFrame   =   myFrames[Math.floor(Math.random()   *   4)];   
//   Now   go   to   the   random   frame
//   然后跳到该LABEL播放
gotoAndStop(randomFrame);   
而数组包含数据的个数称为长度(length),例如fruitList.length   就等于2   
对数组最常用的处理就是从数组中选出有用的数据了,来看一个运用循环的例子:
//   Create   an   array   建立数组,里面放了一些歌的类型
var   soundtracks   =   ["electronic",   
"hip   hop",
"pop",
"alternative",
"classical"];   
//   Check   each   element   to   see   if   it   contains   "hip   hop"
//   一个循环,检查每一个元素是否等于"hip   hop"这个类型
//   另外,请留意此处MOOCK对FOR的写法,J=0之前有一个VAR,这好象可有可无,其实是一个好习惯!
for   (var   j   =   0;   j   <   soundtracks.length;   j++)   {
trace("now   examining   element:   "   +   j);
if   (soundtracks[j]   ==   "hip   hop")   {
trace("the   location   of   ''hip   hop''   is   index:   "   +   j);
break;   //   跳出循环,找到了就不用再找了
}
}   
关于数组的方法(method)
方法就是从属于某一对象(object)的函数,通常都是对该对象进行处理的函数
好象太抽象了?我们还没讲到什么是对象,其实数组是对象的一种,我们就暂且将数组的方法理解为一个专门处理数组内数据的结构和内容的工具吧
例如一个叫push()的方法就是一个工具,用于为数组添加一个元素,并且加在该数组的最后
使用起来并不复杂,看例子就知:
//   Create   an   array   with   2   elements
var   menuItems   =   ["home",   "quit"];   
//   Add   an   element   加一个元素
//   menuItems   becomes   ["home",   "quit",   "products"]
//   现在数组的结构变成["home",   "quit",   "products"]
menuItems.push("products");   
//   Add   two   more   elements   这次是加两个
//   menuItems   becomes   ["home",   "quit",   "products",   "services",   "contact"]
menuItems.push("services",   "contact");   
跟push()相反从最后弹出一个元素的方法是pop()
而跟push()类似,但是是将一个元素加到数组的开头的方法是unshift(),与之相反的是shift()
方法sort和reverse,用于重新排列数组的元素
方法splice用于从数组中间删除某元素
方法slice和concat可以在某些数组的基础上生成另一个新的数组
方法toString和join可以将整个数组变成单一个字符串   
网友评论
相关搜索
阿里西西Baidu.com搜索