JavaScript Tutorial/Array/Array Index

Материал из Web эксперт
Перейти к: навигация, поиск

Append elements to Array by using the index

<html>
<head>
<title>Append elements to Array by using the index</title>
</head>
<body>
<P>
<script language="javascript" type="text/javascript">
<!--
var myArray = new Array();
myArray[0] = "AAA";
myArray[1] = "BBB";
myArray[2] = "CCC";
for (var i=0; i<myArray.length; i++) {
  document.write("Element " +i+ " contains: " +myArray[i]+ "<br />");
}
//-->
</script>
</p>
</body>
</html>


Reference array element by random index value

<html>
<head>
<title>Example</title>
</head>
<body>
<script type="text/javascript">
function selectFrom(iFirstValue, iLastValue) {
    var iChoices = iLastValue - iFirstValue + 1;
    return Math.floor(Math.random() * iChoices + iFirstValue);
}
var aColors = ["A", "B", "C", "D", "E", "F", "G"];
var index = selectFrom(0, aColors.length-1);
var sColor = aColors[index];
alert(sColor);
</script>
</body>
</html>


Reference array value by index

<html>
<head>
<title>A Simple Page</title>
<script language="javascript">
<!--
var days_of_week = new Array(7);
days_of_week[0] = "Sunday";
days_of_week[1] = "Monday";
days_of_week[2] = "Tuesday";
days_of_week[3] = "Wednesday";
days_of_week[4] = "Thursday";
days_of_week[5] = "Friday";
days_of_week[6] = "Saturday";
alert(days_of_week[2]);
//  -->
</script>
</head>
<body>
</body>
</html>


Use for each loop to assign array element value

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
var myarray = new Array("","","","","","","","","","");
for (x in myarray)
{
    myarray[x] = "img" + x + ".gif";
}
document.write(myarray);
//  -->
</script>
</head>
<body>
</body>
</html>


Use variable as the array index

<html>
<head>
<title>A Simple Page</title>
<script language="javascript">
<!--
var days_of_week = new Array(7);
days_of_week[0] = "Sunday";
days_of_week[1] = "Monday";
days_of_week[2] = "Tuesday";
days_of_week[3] = "Wednesday";
days_of_week[4] = "Thursday";
days_of_week[5] = "Friday";
days_of_week[6] = "Saturday";
var x = 2;
alert(days_of_week[x]);
//  -->
</script>
</head>
<body>
</body>
</html>