TypeScript Array (array)
Array objects use individual variable names to store a series of values.
Arrays are very commonly used.
If you have a set of data (for example: website name), there are separate variables as follows:
var site1="Google";
var site2="Runoob";
var site3="Taobao";
If there are 10 or 100, this method becomes very impractical. At this time, we can use an array to solve it:
var sites:string[];
sites = ["Google","Runoob","Taobao"]
This looks much simpler.
The syntax for declaring an array in TypeScript is as follows:
var array_name[:datatype]; //声明
array_name = [val1,val2,valn..] //初始化
Or initialize directly at declaration time:
var array_name[:data type] = [val1,val2…valn]
If the type is not set when the array is declared, it will be considered as any type, and the type of the array will be inferred according to the type of the first element during initialization.
example
Create an array of type numbers:
var numlist:number[] = [2,4,6,8]
The entire array structure looks like this:
The first index value is 0, we can access the array elements according to the index value:
TypeScript
var sites:string[];
sites = ["Google","Runoob","Taobao"]
console.log(sites[0]);
console.log(sites[1]);
Compile the above code to get the following JavaScript code:
JavaScript
var sites;
sites = ["Google", "Runoob", "Taobao"];
console.log(sites[0]);
console.log(sites[1]);
The output is:
Google
Runoob
The following instances we initialize directly when declaring:
TypeScript
var nums:number[] = [1,2,3,4]
console.log(nums[0]);
console.log(nums[1]);
console.log(nums[2]);
console.log(nums[3]);
Compile the above code to get the following JavaScript code:
JavaScript
var nums = [1, 2, 3, 4];
console.log(nums[0]);
console.log(nums[1]);
console.log(nums[2]);
console.log(nums[3]);
The output is:
1
2
3
4
Array object
We can also create arrays using the Array object.
The Array object's constructor accepts the following two values:
- A numeric value representing the size of the array.
- Initialized array list with elements separated by commas.
example
Specify the array initialization size:
TypeScript
var arr_names:number[] = new Array(4)
for(var i = 0; i<arr_names.length; i++) {
arr_names[i] = i * 2
console.log(arr_names[i])
}
Compile the above code to get the following JavaScript code:
JavaScript
var arr_names = new Array(4);
for (var i = 0; i < arr_names.length; i++) {
arr_names[i] = i * 2;
console.log(arr_names[i]);
}
The output is:
0
2
4
6
In the following example we directly initialize the array elements:
TypeScript
var sites:string[] = new Array("Google","Runoob","Taobao","Facebook")
for(var i = 0;i<sites.length;i++) {
console.log(sites[i])
}
Compile the above code to get the following JavaScript code:
JavaScript
var sites = new Array("Google", "Runoob", "Taobao", "Facebook");
for (var i = 0; i < sites.length; i++) {
console.log(sites[i]);
}
The output is:
Google
Runoob
Taobao
Facebook
array destructuring
We can also assign array elements to variables as follows:
TypeScript
var arr:number[] = [12,13]
var[x,y] = arr // 将数组的两个元素赋值给变量 x 和 y
console.log(x)
console.log(y)
Compile the above code to get the following JavaScript code:
JavaScript
var arr = [12, 13];
var x = arr[0], y = arr[1]; // 将数组的两个元素赋值给变量 x 和 y
console.log(x);
console.log(y);
The output is:
12
13
array iteration
We can use the for statement to loop through the individual elements of the output array:
TypeScript
var j:any;
var nums:number[] = [1001,1002,1003,1004]
for(j in nums) {
console.log(nums[j])
}
Compile the above code to get the following JavaScript code:
JavaScript
var j;
var nums = [1001, 1002, 1003, 1004];
for (j in nums) {
console.log(nums[j]);
}
The output is:
1001
1002
1003
1004
Multidimensional Arrays
The elements of an array can be another array, thus forming a multi-dimensional array (Multi-dimensional Array).
The simplest multidimensional array is a two-dimensional array, defined as follows:
var arr_name:datatype[][]=[ [val1,val2,val3],[v1,v2,v3] ]
example
Define a two-dimensional array with three elements in each dimension.
TypeScript
var multi:number[][] = [[1,2,3],[23,24,25]]
console.log(multi[0][0])
console.log(multi[0][1])
console.log(multi[0][2])
console.log(multi[1][0])
console.log(multi[1][1])
console.log(multi[1][2])
Compile the above code to get the following JavaScript code:
JavaScript
var multi = [[1, 2, 3], [23, 24, 25]];
console.log(multi[0][0]);
console.log(multi[0][1]);
console.log(multi[0][2]);
console.log(multi[1][0]);
console.log(multi[1][1]);
console.log(multi[1][2]);
The output is:
1
2
3
23
24
25
Use of arrays in functions
passed as a parameter to the function
TypeScript
var sites:string[] = new Array("Google","Runoob","Taobao","Facebook")
function disp(arr_sites:string[]) {
for(var i = 0;i<arr_sites.length;i++) {
console.log(arr_sites[i])
}
}
disp(sites);
Compile the above code to get the following JavaScript code:
JavaScript
var sites = new Array("Google", "Runoob", "Taobao", "Facebook");
function disp(arr_sites) {
for (var i = 0; i < arr_sites.length; i++) {
console.log(arr_sites[i]);
}
}
disp(sites);
The output is:
Google
Runoob
Taobao
Facebook
as the return value of the function
TypeScript
function disp():string[] {
return new Array("Google", "Runoob", "Taobao", "Facebook");
}
var sites:string[] = disp()
for(var i in sites) {
console.log(sites[i])
}
Compile the above code to get the following JavaScript code:
JavaScript
function disp() {
return new Array("Google", "Runoob", "Taobao", "Facebook");
}
var sites = disp();
for (var i in sites) {
console.log(sites[i]);
}
The output is:
Google
Runoob
Taobao
Facebook
array method
The following table lists some commonly used array methods:
serial number | Method & Description | example |
---|---|---|
1. | concat() concatenates two or more arrays and returns the result. | var alpha = ["a", "b", "c"]; var numeric = [1, 2, 3]; var alphaNumeric = alpha.concat(numeric); console.log("alphaNumeric : " + alphaNumeric ); // a,b,c,1,2,3 |
2. | every() checks whether every element of the numeric element meets the condition. | function isBigEnough(element, index, array) { return (element >= 10); } var passed = [12, 5, 8, 130, 44].every(isBigEnough); console.log("Test Value : " + passed ); // false |
3. | filter() detects numeric elements and returns an array of all elements matching the criteria. | function isBigEnough(element, index, array) { return (element >= 10); } var passed = [12, 5, 8, 130, 44].filter(isBigEnough); console.log("Test Value : " + passed ); // 12,130,44 |
4. | forEach() executes the callback function once for each element of the array. | let num = [7, 8, 9]; num.forEach(function (value) { console.log(value); }); Compile to JavaScript code: var num = [7, 8, 9]; num.forEach(function (value) { console.log(value); // 7 8 9 }); |
5. | indexOf() searches for an element in an array and returns its position. If the search cannot be found, the return value is -1, which means there is no item. | var index = [12, 5, 8, 130, 44].indexOf(8); console.log("index is : " + index ); // 2 |
6. | join() puts all the elements of the array into a string. | var arr = new Array("Google","Runoob","Taobao"); var str = arr.join(); console.log("str : " + str ); // Google,Runoob,Taobao var str = arr.join(", "); console.log("str : " + str ); // Google, Runoob, Taobao var str = arr.join(" + "); console.log("str : " + str ); // Google + Runoob + Taobao |
7. | lastIndexOf() Returns the position of the last occurrence of a specified string value, searching backwards and forwards at the specified position in a string. | var index = [12, 5, 8, 130, 44].lastIndexOf(8); console.log("index is : " + index ); // 2 |
8. | map() processes each element of an array with a specified function and returns the processed array. | var numbers = [1, 4, 9]; var roots = numbers.map(Math.sqrt); console.log("roots is : " + roots ); // 1,2,3 |
9. | pop() removes the last element of the array and returns the removed element. | var numbers = [1, 4, 9]; var element = numbers.pop(); console.log("element is : " + element ); // 9 var element = numbers.pop(); console.log("element is : " + element ); // 4 |
10. | push() Adds one or more elements to the end of the array and returns the new length. | var numbers = new Array(1, 4, 9); var length = numbers.push(10); console.log("new numbers is : " + numbers ); // 1,4,9,10 length = numbers.push(20); console.log("new numbers is : " + numbers ); // 1,4,9,10,20 |
11. | reduce() computes an array element into a value (from left to right). | var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; }); console.log("total is : " + total ); // 6 |
12. | reduceRight() computes an array element into a value (from right to left). | var total = [0, 1, 2, 3].reduceRight(function(a, b){ return a + b; }); console.log("total is : " + total ); // 6 |
13. | reverse() reverses the order of the elements of an array. | var arr = [0, 1, 2, 3].reverse(); console.log("Reversed array is : " + arr ); // 3,2,1,0 |
14. | shift() removes and returns the first element of the array. | var arr = [10, 1, 2, 3].shift(); console.log("Shifted value is : " + arr ); // 10 |
15. | slice() takes a portion of an array and returns a new array. | var arr = ["orange", "mango", "banana", "sugar", "tea"]; console.log("arr.slice( 1, 2) : " + arr.slice( 1, 2) ); // mango console.log("arr.slice( 1, 3) : " + arr.slice( 1, 3) ); // mango,banana |
16. | some() Checks whether any element in the array element meets the specified condition. | function isBigEnough(element, index, array) { return (element >= 10); } var retval = [2, 5, 8, 1, 4].some(isBigEnough); console.log("Returned value is : " + retval ); // false var retval = [12, 5, 8, 1, 4].some(isBigEnough); console.log("Returned value is : " + retval ); // true |
17. | sort() sorts the elements of an array. | var arr = new Array("orange", "mango", "banana", "sugar"); var sorted = arr.sort(); console.log("Returned string is : " + sorted ); // banana,mango,orange,sugar |
18. | splice() adds or removes elements from an array. | var arr = ["orange", "mango", "banana", "sugar", "tea"]; var removed = arr.splice(2, 0, "water"); console.log("After adding 1: " + arr ); // orange,mango,water,banana,sugar,tea console.log("removed is: " + removed); removed = arr.splice(3, 1); console.log("After removing 1: " + arr ); // orange,mango,water,sugar,tea console.log("removed is: " + removed); // banana |
19. | toString() converts an array to a string and returns the result. | var arr = new Array("orange", "mango", "banana", "sugar"); var str = arr.toString(); console.log("Returned string is : " + str ); // orange,mango,banana,sugar |
20. | unshift() adds one or more elements to the beginning of the array and returns the new length. |
var arr = new Array("orange", "mango", "banana", "sugar"); var length = arr.unshift("water"); console.log("Returned array is : " + arr ); // water,orange,mango,banana,sugar console.log("Length of the arra |