Javascript基础教程之数组 array
字符串,数值,布尔值都属于离散值(scalar),如果某个变量是离散的,那么任何时候它只有一个值。
如果想使用变量存储一组值,就需要使用数组(array)。
数组是由多个名称相同的树值构成的集合,集合中每个数组都是数组的元素(element),可以使用变量team存储团队里每个成员的名字。
在JavaScript中,数组使用关键字Array声明创建,同事还可以声明变量的长度length。例如
varaTeam=newArray(12);//声明变量的长度
在无法预知数组的最终个数时,声明数组可以不指定具体个数。例如:
varaTeam=newArray();//数组最终个数未知的情况下,可以不声明具体的个数 aTeam[0]=1414; aTeam[1]="北京"; aTeam[2]=0x4; aTeam[3]="ican"; aTeam[4]="red"; aTeam[5]="blue"; aTeam[6]="orange";
另外,可以直接创建数组
varaTeam=newArray("111","blue","red","beijing");
同字符串一样,数组也可以使用length获取和指定数组的长度。
varaTeam=newArray("111","blue","red","beijing"); document.write(aTeam[1]+"<br>"); document.write(aTeam.length+"<br>")
令注:能更深刻的理解数组。
varaTeam=newArray("111","blue","red","beijing"); aTeam[20]="12415" document.write(aTeam[20]+"<br>"); document.write(aTeam.length+"<br>")
另外,数组还可以用[]来定义。中间使用逗号隔开。
sTeam=[10,"5565","北京",33263,"red"] document.write(sTeam[3])//输出33263
数组可以使用toString()方便的转化
sTeam=[10,"5565","pking",33263,"red"] document.write(sTeam.toString())// //输出结果10,5565,pking,33263,red document.write(typeof(ss)); //输出结果string
如果数组转化为字符串不想使用逗号连接,可使用join()方法。
sTeam=[10,"5565","pking",33263,"red"] ss=sTeam.join("-"); dd=sTeam.join("][") //输出结果10,5565,pking,33263,red document.write(ss); document.write(dd); //输出10-5565-pking-33263-red 10][5565][pking][33263][red
对于字符串,JavaScript使用split()转化为数组
varfruit="apple,2151,orange"; sfruit=fruit.split(",") document.write(sfruit);//输出apple,2151,orange document.write(sfruit.join("-"));//输出apple-2151-orange
接上例,javascript提供了reverse()方法使数组反转。
varfruit="apple,2151,orange"; sfruit=fruit.split(",") document.write(sfruit);//输出apple,2151,orange document.write(sfruit.join("-")+"<br>");//输出apple-2151-orange document.write(sfruit.reverse()+"<br>");输出orange,2151,apple document.write(sfruit.reverse().toString()+"<br>");输出apple,2151,orange
对于字符串反转,javascript没有直接的转化方法,我们可以利用split()将字符串转为数组,利用rerverse()进行反转,再利用join进行连接,达到字符串反转。
varfruit="2151,orange,apple"; varsfruit="iambeijing123"; document.write(fruit.split(",").reverse()+"<br>");//2151,orange,apple document.write(sfruit.split("").reverse().join("")+"<br>");//输出iambeijing123
利用sort()可以使数组元素进行(字母顺序)排序。
fruit=["orange2","2151","orange","apple"] document.write(fruit.sort());//输出结果2151,apple,orange,orange2
关于push()和pop()的用法
sfruit=newArray(); sfruit.push("red"); sfruit.push("green"); sfruit.push("oragen"); sfruit.push("blue"); document.write(sfruit.length+sfruit.toString()+"<br>"); varwfruit=sfruit.pop(); document.write(wfruit+"<br>") document.write(sfruit.toString())
如上,javascript将数组看成了一个堆栈,通过push()和pop()进行压栈和出栈处理。