JavaScript for Array method

 JavaScript Array has the characteristics and structure that an array should have. In other words, in addition to declaring an array, we can of course store the array key or array value we want to store in this array, or we can call it out at any time and store it in advance. When the size of JavaScript Array is small, in fact, you only need to write the data directly to create an array, but when the amount of data is large, you should use JavaScript loops such as JavaScript for or JavaScript while . It is efficient to deal with it in a circle. This article mainly uses JavaScript for loop to introduce how to create an array and call the content of an array.


JavaScript for Array example 1: Create an array through the for loop
<script language='javascript'>
var ArrTest = new Array(); // Declare a new array as ArrTest
for(i=0;i<10;i++){
 ArrTest[i]=i; // Start creating array
}
if(Array.isArray(ArrTest)){
 document.write("ArrTest is still an array");
}
</script>
The above output result: ArrTest is still an array.

At the beginning of the example, we first declare an empty new array ArrTest, and use JavaScript for loops to sequentially bring the numbers into the array, creating an array key (Array Key) starting from 0 to 9 The scale of the end and the corresponding array value are also the same number. The if condition judgment is only used to test whether the nature of the ArrTest array remains unchanged after the for loop. The Array.isArray function can judge whether ArrTest is an array. This is a simple way to create an array using a for loop. The second example below will use the for loop again to output each key and value of the array to the screen.

JavaScript for Array example 2: Output array through for loop
<script language='javascript'>
var ArrTest = new Array(); // Declare a new array as ArrTest
for(i=0;i<10;i++){
 ArrTest[i]=i; // Start creating array
}
for(i=0;i<10;i++){
 document.write(ArrTest[i]); // start outputting array
}
</script>
The above output result: 0123456789

There are two for loops in this example. The first for loop is the same as in Example 1, and the second for loop is used to display data. The number range of i is also from 0 to 9. In this way, the newly created array can be completely output, where document.write is the syntax output to the screen. Combining the above two examples, it should be easy to see how to create an array and how to call an array in the for loop.

Post a Comment

0 Comments