length

Property of

Array

Description

An integer that specifies the number of elements in an array. You can set the length property to truncate an array at any time. You cannot extend an array; for example, if you set length to 3 when it is currently 2, the array will still contain only 2 elements. The length property is static.

Examples

In the following example, the getChoice function uses the length property to iterate over every element in the musicType array. musicType is a select element on the musicForm form.

function getChoice() {
      for (var i = 0; i < document.musicForm.musicType.length; i++) {
            if (document.musicForm.musicType.options[i].selected == true) {
                  return document.musicForm.musicType.options[i].text
            }
      }
}

The following example shortens the array statesUS to a length of 50 if the current length is greater than 50.

if (statesUS.length > 50) {
      statesUS.length=50
      alert("The U.S. has only 50 states. New length is " + statesUS.length)
}