TypeScript 배열 조작

8543 단어 TypeScript
배열 은 매우 간단 한 데이터 구조 이지 만 TypeScript 의 배열 을 사용 할 때마다 어떻게 사용 하 는 지 잊 어 버 리 고 아예 건어물 으로 만들어 보 는 것 을 잊 어 버 렸 다.
1. 배열 의 성명
let array1:Array;
let array2:number[];

2. 배열 초기 화
let array1:Array = new Array();
let array2:number[] = [123];

3. 배열 요소 할당, 추가, 변경
let array:Array = [1,2,3,4];
console.log(array)      // [1, 2, 3, 4]

array[0] = 20;          //   
console.log(array)      // [20, 2, 3, 4]

array[4] = 5;           //   
console.log(array)      // [20, 2, 3, 4, 5]

array.push(6);          //   
console.log(array)      // [20, 2, 3, 4, 5, 6]

array.unshift(8, 0);    //           
console.log(array);     // [8, 0, 20, 2, 3, 4, 5, 6]

삭제
let array:Array = [1,2,3,4];
console.log(array)      // [1, 2, 3, 4]

let popValue = array.pop();     //   
console.log(array)      // [1, 2, 3]

array.splice(0, 1);     //     (index, deleteCount)
console.log(array)      // [2, 3]

array.shift();          //        
console.log(array);     // [3]

5. 합병, 차단 배열
/**
  * 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[];
/**
 *                   
 */
slice(start?: number, end?: number): T[];
let array: Array = [1, 2, 3];
let array2: Array = [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. 배열 요소 위치 찾기
/**
  *                
  */
indexOf(searchElement: T, fromIndex?: number): number;
/**
  *                 
  */
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. 연결 배열 요소
/**
 *     
 */
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. 정렬, 역순 배열
let array:Array = [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]

여기 전편 을 보 세 요

좋은 웹페이지 즐겨찾기