Truncating and Iterating Array Elements

This section provides a tutorial example on how to use the array length to truncate and iterate over array elements.

As an object, an array has a special property called "length". You can use the object dot (.) operator to retrieve the length value: "array_name.length".

The array length property can be used to truncate an array by setting the "length" property to a lower value.

The array length property is also useful when you want to iterate all elements of an array.

For example, iterating all elements of an array with a "for" loop can be done as:

for (var i = 0; i < array_name.length; i++) {
  ... array_name[i];
}

Here is a tutorial example JavaScript that shows you how to truncate and iterate array elements with the "length" property:

<html>
<!-- Loop_Array_Elements.html
    Copyright (c) 2002 HerongYang.com. All Rights Reserved.
->
<head><title>Loop Array Elements</title></head>
<body>
<pre>
<script type="text/javascript">

   // Creating an empty array
   var even_numbers = new Array();

   // Storing 20 elements in the array
   for (var i=0; i<20; i++) {
      even_numbers[i] = i*2;
   }

   // Truncating the array length to 10
   even_numbers.length = 10;
   
   // Iterating all 10 elements
   document.write("First 10 even numbers: ");
   for (var i=0; i<even_numbers.length; i++) {
      document.write(even_numbers[i]+", ");
   }
</script>
</pre>
</body>
</html>

The output of this sample JavaScript is:

First 10 even numbers: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 

Table of Contents

 About This Book

 Introduction to JavaScript

 ECMAScript Language Specification and JavaScript Dialects

 Data Types, Variables and Expressions

 Flow Control Statements

Creating, Accessing, and Manipulating Arrays

 What Is an Array

 Creating an Array Object

 Accessing Array Elements with Indexes

Truncating and Iterating Array Elements

 Array Object Instance Methods

 Array Object Instance Method Examples

 Defining and Calling Functions

 Web Browser Supporting JavaScript

 Server-Side and Client-Side Web Scripting

 Introduction to Objects

 Defining Your Own Object Types

 Inheritance of Properties and Methods through the Prototype Object Chain

 'jrunscript' - JavaScript Shell Command from JDK

 Using Functions as "Function" Objects

 Introduction to Built-in Object Types

 W3C's Document Object Model (DOM) Specifications

 AJAX (Asynchronous JavaScript And XML)

 References

 Full Version in PDF/EPUB