Online Documentation Server
 ПОИСК
ods.com.ua Web
 КАТЕГОРИИ
Home
Programming
Net technology
Unixes
Security
RFC, HOWTO
Web technology
Data bases
Other docs

 


 ПОДПИСКА

 О КОПИРАЙТАХ
Вся предоставленная на этом сервере информация собрана нами из разных источников. Если Вам кажется, что публикация каких-то документов нарушает чьи-либо авторские права, сообщите нам об этом.




Previous Table of Contents Next

Chapter 13
Arrays

What is an Array?

Arrays are data structures, somewhat more complex than simple variables. As a matter of fact, an array in JavaScript is a set of variables with the same name. We use arrays when we want to work with a certain block of data. As a programmer, if you want to process an individual item of an array you need to specify the array name and indicate which array element is being referenced. Specific elements are indicated by an index or a subscript. This way you can have endless variables defined quickly and acted upon either individually or as a group.

If you are constructing a building you need bricks. Naming each brick (“Arthur”, “Jordan”, ...) is fine for a small number of bricks. Such bricks are known as variables in JavaScript. Sometimes you want to refer to tens, hundreds, or even more bricks. It would be difficult to name each brick separately. A much more convenient naming scheme is “brick 0”, “brick 1”, “brick 2”, “brick 3”, and so forth. Arrays allow us to do that with variables. An array is a set of memory locations used to store data. Each item in an array is called an element.

Some History

The first version of JavaScript, the one supported by Navigator 2.x, did not feature arrays. This was very strange because whether it is a scripting language like Perl, or a programming language like C++, it must have an explicit array type. JavaScript scripters had no choice but to come up with a simple workaround. Everyone used (and most still use) the following function to create arrays:

function createArray(n, init) {
  this.length = n
  for (i = 1 ; i <= n ; i++) {
 this[i] = init
  }
}

Some variants of this function did not include the size specification, or did not include the init parameter, initializing the array to the same value each time. Not only did JavaScript scripters have to use a custom function just to create an array, no built-in methods or functions were available to deal with such arrays. Sorting arrays became a difficult, inefficient task. Combining arrays was even more difficult. It was obvious that a change needed to be made. And indeed, Netscape Navigator 3.0 introduced a whole new version supporting arrays.

Creating Simple Arrays

Arrays in JavaScript are simple built-in objects. You create an array just like an instance of an object, because that is exactly what it is. The formal name of the object is Array—notice the capitalized “A.” The general syntax is:

var arrayObjectName = new Array()
var arrayObjectName = new Array(arrayLength)

arrayObjectName is either the name of a new object, an existing variable, or a property of an existing object.

arrayLength is the initial length of the array. You can access this value using the length property.

As you can see, specifying the length of the array or the number of elements is not vital. An array is an object like any other object. There is no explicit array type in JavaScript.

Here are some arrays:

var day = new Array(31)
var month = new Array(12)
var year = new Array() // number of years "not known"

It is unnecessary to understand how arrays correspond with the computer memory because you will not need to use lots of memory in any of your scripts, so let JavaScript do the job for you.

All elements of an array are initially null. This is important because such elements do not have any influence on your script. An element with a null value actually does not exist. You can prove this to yourself by running the getProps() on a new array:

function getProps(obj, objName) {
  var result = ""
  for (var i in obj) {
 if (typeof obj[i] == "object")
result += getProps(obj[i], objName + "[" + i + "]")
 else
result += objName + "[" + i + "] = " + obj[i] + "<BR>"
  }
  return result
}

var ar = new Array(3)

document.write(getProps(ar, "ar"))

This script does not generate any output, because if a property of an object has a null value, it does not exist in the computer memory, so it is not recognized.

Strongly typed programming languages require that you specify the number of elements in an array. In such languages all elements of an array must contain values of the same type (int, char, ). An array is an explicit data structure in those languages, so it is not an object as in JavaScript. null values are not given to the elements of an array. From the moment an array is declared, it takes up the required storage area in memory. It does not matter if you initialized its values or not. Theoretically, if you created an array without specifying the number of elements, it would be as if you created one with zero elements. Extending an array in such languages is usually not possible; therefore you must specify the length in all array declarations.

The null value is given by default to each element of an array in JavaScript. When the value is null, the element is not stored in the computer’s memory. So creating an array with an infinite number of elements is fine in JavaScript. Keep in mind that elements holding a null value do not take up space in memory, but they are considered elements in the array, so they are added to the array’s length property.

With JavaScript, like Perl and unlike C++, it doesn’t matter whether the elements of an array are of the same data type. They can be a mix of numbers, strings, Boolean values, objects, and even arrays (which are actually objects).

Referring to an Array’s Elements

To use an event you must be able to refer to its elements. Arrays in JavaScript are objects. Like all other objects, they have properties and methods:

arrayObjectName.propertyName // ar1.length
arrayObjectName[subscript] // ar1[4]
arrayObjectName.methodName(arguments)

In this section we will discuss the second reference, whereas the others are presented later in the chapter.

The subscript follows the array name and is enclosed in square brackets. Subscripts are simple integers which start at zero.

Here is a simple array:

var ar = new Array(5)

This array has five elements: ar[0], ar[1], ar[2], ar[3], ar[4].

Previous Table of Contents Next


With any suggestions or questions please feel free to contact us