Source: https://blog.csdn.net/honey199396/article/details/80750408
Array is a very simple data structure, but every time you use TypeScript array, you always forget how to use it. Just make it dry and forget to come and have a look.
1, Declaration of array
let array1:Array<number>; let array2:number[];
2, Array initialization
let array1:Array<number> = new Array<number>(); let array2:number[] = [1,2,3];
3, Array element assignment, addition, change
let array:Array<number> = [1,2,3,4]; console.log(array) // [1, 2, 3, 4] array[0] = 20; // modify console.log(array) // [20, 2, 3, 4] array[4] = 5; // assignment console.log(array) // [20, 2, 3, 4, 5] array.push(6); // Add to console.log(array) // [20, 2, 3, 4, 5, 6] array.unshift(8, 0); // Add in the first place console.log(array); // [8, 0, 20, 2, 3, 4, 5, 6]
Four, delete
let array:Array<number> = [1,2,3,4]; console.log(array) // [1, 2, 3, 4] let popValue = array.pop(); // Eject console.log(array) // [1, 2, 3] array.splice(0, 1); // Delete element (index, deleteCount) console.log(array) // [2, 3] array.shift(); // Delete first element console.log(array); // [3]
5, Merging and breaking arrays
/** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ concat(...items: T[][]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ concat(...items: (T | T[])[]): T[]; /** * This method returns a new array of specified starting positions */ slice(start?: number, end?: number): T[];
let array: Array<number> = [1, 2, 3]; let array2: Array<number> = [4, 5, 6]; let arrayValue = 7; array = array.concat( array2); console.log(array) // [1, 2, 3, 4, 5, 6] array = array.concat(arrayValue); console.log(array) // [1, 2, 3, 4, 5, 6, 7] let newArray = array.slice(2, 4); console.log(newArray) // [3, 4]
6, Find array element location
/** * Returns the location of the first element found */ indexOf(searchElement: T, fromIndex?: number): number; /** * Returns the location of the first element found in reverse order */ lastIndexOf(searchElement: T, fromIndex?: number): number;
let array: Array<string> = ["a","b","c","d","c","a"]; let indexC = array.indexOf("c"); console.log(indexC); // 2 let lastA = array.lastIndexOf("a"); console.log(lastA); // 5
7, Connect array elements
/** * Linked array */ join(separator?: string): string;
let array: Array<string> = ["a","b","c","d","c","a"]; let result = array.join(); console.log(result); // a,b,c,d,c,a result = array.join("+"); console.log(result); // a+b+c+d+c+a result = array.join(""); console.log(result); // abcdca
8, Sort, reverse array
let array:Array<number> = [3, 2, 1, 8, 7, 0, 4]; console.log(array); // [3, 2, 1, 8, 7, 0, 4] array.sort(); console.log(array); // [0, 1, 2, 3, 4, 7, 8] array.reverse(); console.log(array); // [8, 7, 4, 3, 2, 1, 0]
9, Traverse here Last article