JavaScript - 数组方法应用
数组方法应用
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>数组方法应用</title>
<script type="text/javascript">
var nums=new Array();
var names=new Array(3);
names[0]="tom";
names[1]="jack";
names[2]="mike";
names[3]="alice";
names[4]="alex";
//创建数组的两种方式
var stus1=new Array("zhangsan","lisi","wangwu");
var stus2=["hehe","heihei","haha","hoho"];
names.sort(); //升序
names.reverse(); //反转
//for循环遍历数组
for(var i=0;i<names.length;i++){
document.writeln(names[i]+" ");
}
document.writeln("<br/>");
//foreach遍历时获取的是数组的下标
for(var j in stus2){
document.writeln(j+":"+stus2[j]);
}
document.writeln("<br/>");
//以指定的字符拼接数组中的元素
var str=names.join(",");
document.writeln(str);
document.writeln("<br/>");
//在JavaScript中,数组的索引可以是数字,也可以是字符串
var citys=new Array(3);
citys["nanjing"]="南京";
citys["beijing"]="北京";
citys["tianjing"]="天津";
for(var c in citys){
document.writeln(c+":"+citys[c]+"<br/>");
}
document.writeln("<br/>");
//二组数组
var grade=new Array(3);
grade["wbs14061"]=new Array("小涛","超哥","程程");
grade["wbs14081"]=new Array("小朋朋","中朋朋","db朋朋");
grade["wbs14091"]=new Array("小李子","小狗子","小驴子");
//输出所有班级学生信息
for(var gradeName in grade){
document.writeln(gradeName+":")
for(var stu in grade[gradeName]){
document.writeln(grade[gradeName][stu]+" ")
}
document.writeln("<br/>");
}
document.writeln("<br/>");
</script>
</head>
<body>
</body>
</html>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。