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

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()
主站蜘蛛池模板: 仙桃市| 英德市| 镇沅| 中宁县| 泾阳县| 岑溪市| 东平县| 新绛县| 高清| 崇州市| 临海市| 申扎县| 卢氏县| 乌拉特前旗| 台前县| 大厂| 建德市| 灵宝市| 瑞丽市| 盐城市| 岑巩县| 右玉县| 黄山市| 犍为县| 陵川县| 宜春市| 藁城市| 鹿泉市| 图们市| 涟源市| 余庆县| 腾冲县| 眉山市| 夏邑县| 克东县| 锡林郭勒盟| 利津县| 潮安县| 淮北市| 嵊泗县| 江城|