number

  • 소수점 반올림
const n: number = 3.14159
console.log(n.toFixed(3)); // 3.142
  • 최소, 최대값
console.log(Number.POSITIVE_INFINITY); // Infinity
console.log(Number.NEGATIVE_INFINITY); // -Infinity

string

  • char to ascii
const s: string = 'ABC';
console.log(s.charCodeAt(0)); // 65
  • ascii to char
const n: number = 0x41;
console.log(String.fromCharCode(n)); // A

array

  • 2차원 배열
const arr: Array<Array<number>> = Array.from(Array(5), () => Array(3).fill(0));
// 0으로 초기화된 5행 3열 2차원 배열 생성
  • 누적값
const n: number[] = [1, 2, 3, 4];
console.log(n.reduce((s, c) => s+c, 0)); // 10
/* 
  s : 누적값
  c : 현재값
  i(생략) : 인덱스
  0 : s의 초기값
*/
  • 순회
const n: number[] = [1, 2, 3, 4];
console.log(n.map(v => v+2)); // [3, 4, 5, 6]
  • array to string
const s: string[] = ['a', 'b', 'c'];
console.log(s.join()); // a,b,c
console.log(s.join('')); // abc
  • 정렬
const n: number[] = [1, 100, 10];
console.log(n.sort()); // [1, 10, 100]

const compare = (a: number, b: number) => b-a;
console.log(n.sort(compare)); // [100, 10, 1]
  • 배열 이어붙이기
const arr1: Array<number> = [1, 2, 3];
const arr2: Array<number> = [4, 5, 6];
arr1.push(...arr2) // 전개 연산자 활용
console.log(arr1); // [1, 2, 3, 4, 5, 6]

Math

  • 소수점 올림, 버림, 반올림
const n = 1.4;
console.log(Math.ceil(n)); // 올림, 2
console.log(Math.floor(n)); // 버림, 1
console.log(Math.round(n)); // 반올림, 1

기타

  • number to string
const n: number = 123;
for(let c of String(n)) console.log(c, typeof(c));
// 1 string
// 2 string
// 3 string
  • 전개 연산자
const n: number[] = [1, 2, 3, 4];
const [a, ...b] = n;

console.log(a, b); // 1 [2, 3, 4]
console.log([...b, a]); // [2, 3, 4, 1]

참고

댓글