javascrip 建立數組
建立數組
有幾種不同的方法來建立一個數組。建立數組的數組參與()構造舊的方式。
JavaScript數組是動態,你可以聲明一個數組,不通過任何與陣列參數()構造。
在這種情況下,您將建立一個沒有元素的空數組。
Select ActionSelect AllTry It<script type="text/javascript教程">
//We initialize the array using the array() constructor.
var first_array = new Array();
first_array[0] = "This is an element";
first_array[1] = 5;
first_array[2] = "JavaScript - Tutorial";
first_array[3] = 16;
first_array[4] = 7;
var counter=0;
//Let's print out the elements of the array.
for (counter=0; counter<first_array.length; counter++)
document.write(first_array[counter] + "<br>");
</script>
Select ActionSelect AllTry It<script type="text/javascript">
//We declare the first array and pass a single integer as an argument..
var cars = new Array(5);
cars[0] = "Audi";
cars[1] = "Bentley";
cars[2] = "Mercedes";
cars[3] = "Mini";
cars[4] = "BMW";
//Now we declare the second array and pass 8 arguments.
//This technique does not work in JavaScript 1.2.
var flowers = new Array("Rose", 2.45, "Daisy", 1.57, "Orchild", 0.75,
"Tulip", 1.15);
var counter=0;
document.write("<h1>Elements of the first array:</h1>");
for (counter=0; counter<cars.length; counter++)
document.write(cars[counter] + "<br>");
counter=0;
document.write("<h1>Elements of the second array:</h1>");
for (counter=0; counter<flowers.length; counter++) {
if (counter % 2 == 0) {
document.write(flowers[counter] + " costs ");
}
else {
document.write(flowers[counter] + "<br>");
}
}
</script>