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

Arrays

Arrays are structures that TypeScript inherits from JavaScript. We add type annotations to arrays as usual, but with square brackets at the end to denote that this is an array type.

Let's take a look at an example:

  1. Let's declare the following array of numbers in the TypeScript playground:
const numbers: number[] = [];

Here, we have initialized the array as empty.

  1. We can add an item to the array by using the array's push function. Let's add the number 1 to our array:
numbers.push(1);
We used const to declare the numbers variable and was able to change its array elements later in the program. The array reference hasn't changed – just the elements within it. So, this is fine with the TypeScript compiler.
  1. If we add an element with an incorrect type, the TypeScript compiler will complain, as we would expect:

  1. We can use type inference to save a few keystrokes if we declare an array with some initial values. As an example, if we type in the following declaration and hover over the numbers variable, we'll see the type has been inferred as number[].
const numbers = [1, 3, 5];
  1. We can access an element in an array by using the element number in square brackets. Element numbers start at 0.

Let's take an example:

  1. Let's log out the number of elements under the numbers variable declaration, as follows:
console.log(numbers[0]); 
console.log(numbers[1]);
console.log(numbers[2]);
  1. Let's now click the Run option on the right-hand side of the TypeScript playground to run our program. A new browser tab should open with a blank page. If we press F12 to open the Developer tools and go to the console section, we'll see 1, 3, and 5 output to the console.
  1. There are several ways to iterate through elements in an array. One option is to use a for loop, as follows:
for (let i in numbers) {
console.log(numbers[i]);
}

If we run the program, we'll see 1, 3, and 5 output to the console again.

  1. Arrays also have a useful function for iterating through their elements, called forEach. We can use this function as follows:
numbers.forEach(function (num) {
console.log(num);
});
  1. forEach calls a nested function for each array element, passing in the array element. If we hover over the num variable, we'll see it has been correctly inferred as a number. We could have put a type annotation here, but we have saved ourselves a few keystrokes:

Arrays are one of the most common types we'll use to structure our data. In the preceding examples, we've only used an array with elements having a number type, but any type can be used for elements, including objects, which in turn have their own properties.

主站蜘蛛池模板: 中西区| 富源县| 道孚县| 合江县| 安仁县| 余干县| 施甸县| 蓝山县| 仙居县| 崇文区| 虞城县| 常山县| 四子王旗| 汝州市| 香格里拉县| 镇沅| 旌德县| 乌兰察布市| 托克逊县| 垫江县| 丰原市| 慈溪市| 姚安县| 天镇县| 阳东县| 宁海县| 海阳市| 田林县| 容城县| 临泉县| 波密县| 乳山市| 雷山县| 海林市| 齐河县| 江西省| 五寨县| 海兴县| 博乐市| 类乌齐县| 普格县|