官术网_书友最值得收藏!

Arrays

Variables are good to hold single values, but for cases where a variable should contain multiple values, we would have to rely on arrays. A JavaScript array is a collection of items arranged in an order, according to their index. Each item, in the array, is an element and has an index, which is used to access that element. Arrays are like a bookshelf that holds more than one book; each book having its unique location. Arrays are declared using the array literal notation [].

Let us look at a simple array declaration:

Note

Arrays in JavaScript are zero based.

Let us initialize the array:

To access the value of a specific element, the reference index of that element is used. Once the reference index is identified, it can be outputted using the alert statement, as shown in the following screenshot:

Unlike variables, arrays are not typed, therefore, they can contain various types of data, as shown in the following screenshot:

A much more complex example of a JavaScript array is a multidimensional array, where there is a combination of arrays inside an array, as seen in the following screenshot:

To retrieve an element from a multidimensional array, we would have to use as many indexes as the levels in that array. If the multidimensional array contains an array that has the values that we want to access, we will have to choose the index where the array element exists, and then choose the index of the value inside the array that we are searching for. To retrieve the string Three from the multidimensionalArray example, we will have to first locate the index of the array containing the value Three, and then find the index of the value Three inside that array. This is shown as follows:

Note

The second way of declaring an array is by using the Array class.

var bookshelf = new Array()
主站蜘蛛池模板: 唐山市| 乌拉特后旗| 浦东新区| 松阳县| 富锦市| 南江县| 安义县| 成安县| 澄城县| 满洲里市| 伊川县| 玛曲县| 滨州市| 德惠市| 东明县| 丘北县| 元朗区| 鹤岗市| 大厂| 沛县| 锦州市| 栖霞市| 昌宁县| 永昌县| 福海县| 哈巴河县| 西乌| 高陵县| 荔波县| 隆昌县| 四会市| 浙江省| 沿河| 肃南| 蒲城县| 山东省| 新巴尔虎右旗| 武汉市| 大城县| 炎陵县| 临安市|