Defining arrays
An array object is used to store a series of values in a separate variable name.
We use the keyword new to create an array object. The following code defines an array object named MyArray:
var myarray=new Array ()
There are two ways to assign values to an array (you can add as many values as you want to define as many variables as you need).
1:
var mycars= new Array()
mycars[0]= "Saab" mycars[1]= "Volvo" mycars[2]= "BMW"
You can also use an integer argument to control the capacity of an array:
var mycars= new Array(3)
mycars[0]= "Saab" mycars[1]= "Volvo" mycars[2]= "BMW"
2:
var mycars=new Array("Saab","Volvo","BMW");
遍历数组
<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>
合并数组
<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>
Composing arrays into strings
<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>
Sort string array
<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>
Sorting numeric Arrays
<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>
JavaScript Array Object