javaScript数组对象
定义数组
数组对象用来在单独的变量名中存储一系列的值。
我们使用关键词 new 来创建数组对象。下面的代码定义了一个名为 myArray 的数组对象:
var myArray=new Array()
有两种向数组赋值的方法(你可以添加任意多的值,就像你可以定义你需要的任意多的变量一样)。
1:
var mycars=new Array()
mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"
也可以使用一个整数自变量来控制数组的容量:
var mycars=new Array(3)
mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"
2:
var mycars=new Array("Saab","Volvo","BMW");
遍历数组
<html>
<body>
<script type="text/javascript">
var x
var mycars = new Array()
mycars[0] = "Saab"
mycars[1] = "Volvo"
mycars[2] = "BMW"
for (x in mycars)
{
document.write(mycars[x] + "<br />")
}
</script>
</body>
</html>
合并数组
<html>
<body>
<script type="text/javascript">
var arr = new Array(3)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
var arr2 = new Array(3)
arr2[0] = "James"
arr2[1] = "Adrew"
arr2[2] = "Martin"
document.write(arr.concat(arr2))
</script>
</body>
</html>
将数组组成字符串
<html>
<body>
<script type="text/javascript">
var arr = new Array(3);
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
document.write(arr.join());
document.write("<br />");
document.write(arr.join("."));
</script>
</body>
</html>
字符串数组排序
<html>
<body>
<script type="text/javascript">
var arr = new Array(6)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
arr[3] = "James"
arr[4] = "Adrew"
arr[5] = "Martin"
document.write(arr + "<br />")
document.write(arr.sort())
</script>
</body>
</html>
数字数组排序
<html>
<body>
<script type="text/javascript">
function sortNumber(a, b)
{
return a - b
}
var arr = new Array(6)
arr[0] = "10"
arr[1] = "5"
arr[2] = "40"
arr[3] = "25"
arr[4] = "1000"
arr[5] = "1"
document.write(arr + "<br />")
document.write(arr.sort(sortNumber))
</script>
</body>
</html>