JavaScript Tutorial/Array/Array Loop

Материал из Web эксперт
Версия от 08:25, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Array Iteration

<HTML>
   <HEAD>
   <TITLE>
   Iteration
   </TITLE>
   </HEAD>
   <BODY>
   <H1>
   <SCRIPT>
      var myArray = new Array(4);
      myArray[0] = "A";
      myArray[1] = "B";
      myArray[2] = "C";
      myArray[3] = "D";
      myArray[6] = "E";
     delete myArray[1]
     for (var i = 0; i < myArray.length; i++){
       if (myArray[i])
        document.write("myArray[" + i + "] = " + myArray[i] + "<br>");
     }     
   </SCRIPT>
   </H1>
   </BODY>
</HTML>


Output all array element with document.write

<html>
<head>
<title>Writing an Array</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>


Use document.write to output the array content

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


Use for each loop to change the array element value

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
var myarray = new Array(5);
myarray[0] = 5
myarray[1] = 8
myarray[2] = 10
myarray[3] = 18
myarray[4] = 180
for (x in myarray)
{
    myarray[x] = ++myarray[x];
}
document.write(myarray);
document.write("<br>");
document.write(x);
//  -->
</script>
</head>
<body>
</body>
</html>


Use for loop to initialize an array

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