YouTip LogoYouTip

Ts Array

Array objects are used to store a series of values under a single variable name. Arrays are very commonly used. Suppose you have a set of data (e.g., website names) stored in separate variables as shown below: var site1="Google"; var site2=""; var site3="Taobao"; If you have 10 or 100 such variables, this method becomes impractical. We can use an array to solve this: var sites:string[]; sites = ["Google","","Taobao"] This looks much cleaner. The syntax for declaring an array in TypeScript is as follows: var array_name[:datatype]; // Declaration array_name = [val1,val2,valn..] // Initialization Or initialize directly during declaration: var array_name[:datatype] = [val1,val2…valn] If the type is not set when declaring the array, it will be considered as type `any`, and the type will be inferred based on the first element during initialization. ### Example Create an array of type `number`: var numlist:number[] = [2,4,6,8] The entire array structure is as follows: !(#) The first index is 0. We can access array elements using the index: ## TypeScript var sites:string[]; sites = ["Google","","Taobao"]console.log(sites); console.log(sites); Compiling the above code yields the following JavaScript code: ## JavaScript var sites; sites = ["Google", "", "Taobao"]; console.log(sites); console.log(sites); The output is: GoogleTutorial In the following example, we initialize directly during declaration: ## TypeScript var nums:number[] = [1,2,3,4]console.log(nums); console.log(nums); console.log(nums); console.log(nums); Compiling the above code yields the following JavaScript code: ## JavaScript var nums = [1, 2, 3, 4]; console.log(nums); console.log(nums); console.log(nums); console.log(nums); The output is: 1 2 3 4 * * * ## Array Object We can also create arrays using the Array object. The Array object constructor accepts the following two types of values: * A number representing the size of the array. * An initialized list of array elements, with values separated by commas. ### Example Specify the initial size of the array: ## TypeScript var arr_names:number[] = new Array(4)for(var i = 0; i<arr_names.length; i++){arr_names = i * 2 console.log(arr_names)} Compiling the above code yields the following JavaScript code: ## JavaScript var arr_names = new Array(4); for(var i = 0; i<arr_names.length; i++){arr_names = i * 2; console.log(arr_names); } The output is: 0246 In the following example, we initialize the array elements directly: ## TypeScript var sites:string[] = new Array("Google","","Taobao","Facebook")for(var i = 0;i<sites.length;i++){console.log(sites)} Compiling the above code yields the following JavaScript code: ## JavaScript var sites = new Array("Google", "", "Taobao", "Facebook"); for(var i = 0; i<sites.length; i++){console.log(sites); } The output is: GoogleTutorialTaobaoFacebook * * * ## Array Destructuring We can also assign array elements to variables, as shown below: ## TypeScript var arr:number[] = [12,13]var[x,y] = arr console.log(x)console.log(y) Compiling the above code yields the following JavaScript code: ## JavaScript var arr = [12, 13]; var x = arr, y = arr; console.log(x); console.log(y); The output is: 1213 * * * ## Array Iteration We can use a `for` statement to loop through and output each element of the array: ## TypeScript var j:any; var nums:number[] = [1001,1002,1003,1004]for(j in nums){console.log(nums)} Compiling the above code yields the following JavaScript code: ## JavaScript var j; var nums = [1001, 1002, 1003, 1004]; for(j in nums){console.log(nums); } The output is: 1001100210031004 * * * ## Multi-dimensional Arrays The elements of an array can be another array, which forms a multi-dimensional array. The simplest multi-dimensional 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 where each dimension's array has three elements. !(#) ## TypeScript var multi:number[][] = [[1,2,3],[23,24,25]]console.log(multi)console.log(multi)console.log(multi)console.log(multi)console.log(multi)console.log(multi) Compiling the above code yields the following JavaScript code: ## JavaScript var multi = [[1, 2, 3], [23, 24, 25]]; console.log(multi); console.log(multi); console.log(multi); console.log(multi); console.log(multi); console.log(multi); The output is: 123232425 * * * ## Using Arrays in Functions ### Passing as a Parameter to a Function ## TypeScript var sites:string[] = new Array("Google","","Taobao","Facebook")function disp(arr_sites:string[]){for(var i = 0;i<arr_sites.length;i++){console.log(arr_sites)}}disp(sites); Compiling the above code yields the following JavaScript code: ## JavaScript var sites = new Array("Google", "", "Taobao", "Facebook"); function disp(arr_sites){for(var i = 0; i= 10); } var passed = [12, 5, 8, 130, 44].every(isBigEnough); console.log("Test Value : " + passed ); // false | | 3. | filter() Creates a new array with all elements that pass the test implemented by the provided function. | 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 a provided function once for each array element. | let num = [7, 8, 9]; num.forEach(function (value) { console.log(value);}); Compiled 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 the array and returns its index. If not found, returns -1, indicating the element is not present. | var index = [12, 5, 8, 130, 44].indexOf(8); console.log("index is : " + index ); // 2 | | 6. | join() Joins all elements of an array into a string. | var arr = new Array("Google","","Taobao"); var str = arr.join(); console.log("str : " + str ); // Google,,Taobao var str = arr.join(", "); console.log("str : " + str ); // Google, , Taobao var str = arr.join(" + "); console.log("str : " + str ); // Google + + Taobao | | 7. | lastIndexOf() Returns the last index at which a given element can be found in the array, searching backwards from the specified position. | var index = [12, 5, 8, 130, 44].lastIndexOf(8); console.log("index is : " + index ); // 2 | | 8. | map() Creates a new array with the results of calling a provided function on every element in the calling 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 from an array and returns that 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 an 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() Applies a function against an accumulator and each value of the array (from left to right) to reduce it to a single value. | var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; }); console.log("total is : " + total ); // 6 | | 12. | reduceRight() Applies a function against an accumulator and each value of the array (from right to left) to reduce it to a single value. | 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 the first element from an array and returns that element. | var arr = [10, 1, 2, 3].shift(); console.log("Shifted value is : " + arr ); // 10 | | 15. | slice() Returns a shallow copy of a portion of an array into a new array object. | 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() Tests whether at least one element in the array passes the test implemented by the provided function. | 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 in place and returns the 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() Changes the contents of an array by removing or replacing existing elements and/or adding new elements. | 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() Returns a string representing the array. | 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 an 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 array is : " + length ); // 5 |
← Ts ClassTs Function β†’