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

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.

主站蜘蛛池模板: 财经| 商丘市| 镇赉县| 太仆寺旗| 黔东| 石渠县| 长海县| 志丹县| 龙南县| 榆中县| 商洛市| 滨海县| 凌云县| 龙胜| 澄城县| 桑植县| 林芝县| 施秉县| 射洪县| 宜昌市| 阳信县| 肥东县| 黑河市| 安塞县| 顺平县| 台山市| 高尔夫| 宜丰县| 高台县| 凤城市| 灵璧县| 连平县| 寿阳县| 安庆市| 双峰县| 绥江县| 镇宁| 汝城县| 南川市| 平利县| 淅川县|