[코테용]JS 메소드 정리

welchs·2021년 1월 21일
0

코테용으로 정리해보기 위한 글입니다.
계속 업데이트할 예정입니다.

1. Array

  • Array.prototype.reverse() : 배열의 순서를 반전시킴

  • Array.prototype.from() : 유사 배열 객체(array-like object)나 반복 가능한 객체(iterable object)를 얕게 복사해새로운Array 객체를 만듦

    사용 예시
    Array.from({ length: 5 }, (v, i) => i); // 결과: [ 0, 1, 2, 3, 4 ]

  • Array.prototype.reduce(acc, cur, index, [, initialValue])
    -> null일경우 initalValue를 안써주면 오류발생가능 initialValue를 가능하면 써주자!

  • 배열에 원하는 수만큼 count하고 싶을때: Array.filter(x => x== 2).length

  • 계단식 2차원배열: const array = new Array(n).fill(0).map((e,i) => new Array(i+1).fill(0));

  • Array.prototype.splice(start[, deleteCount[, item1[, item2[, ,,,)
    -> 한 요소 제거: arr.splice(index, 1);
    -> deleteCount가 0이면 제거 x
    -> splice는 제거뿐아니라 교체, 추가도 가능

  • Array.prototype.indexOf( searchElement[, fromIndex] ) : searchElement의 index를 알려줌, 없으면 -1 반환
    -> 간단한건 이걸 쓰고, 객체내부의 property로 찾아야할경우 findIndex 추천

  • Array.prototype.includes();

  • Array.prototype.flat() : 모든 하위 배열 요소를 지정한 깊이까지 재귀적으로 이어붙인 새로운 배열을 생성

    사용 예시

    const arr2 = [1, 2, [3, 4, [5, 6]]];
    arr2.flat(); // 결과: [1, 2, 3, 4, [5, 6]]
    const arr3 = [1, 2, [3, 4, [5, 6]]];
    arr3.flat(2); // 결과: [1, 2, 3, 4, 5, 6]

2. String

  • String.prototype.match()
    사용법: str.match(regexp) : matching되는 것 없을시 null 반환
    dartResult.match(/([0-9]{1,2}[^0-9]{1,2})/g); // input: '10D#2S*3S', 결과: ['10D#', '2S*', '3S']
    scores = scores.map((el) => el.match(/([0-9]{1,2})(.)(.*)/));
    . : 개행 문자를 제외한 모든 단위문자에 매칭

  • string은 대소비교는 가능하지만 빼기연산은 불가능

  • String.prototype.indexOf() : string에서 해당 요소의 첫번째 index반환 없으면 -1 반환

  • String.prototype.repeat();
    str.repeat(count); : 문자열을 반복할 횟수, count를 자동으로 int변환
    e.g. 'abc'.repeat(2); // 결과: 'abcabc'

  • String.prototype.replaceAll() : 이건 mdn에는 있는데 프로그래머스에서는 없는 function으로 뜨네요... 어차피 Stirng.prototype.replace(regex, replaceString); 해도되긴 합니다.

  • String.prototype.replace()
    e.g. str.replace(/1|0/g, a => +a ? '#' : ' '));
    -> 1이면 #으로 0이면 공백으로바꾸는 예제

  • String.prototype.padStart(targetLength, [, padString] )
    e.g.

'abc'.padStart(10);         // "       abc"
'abc'.padStart(10, "foo");  // "foofoofabc"
  • String.prototype.localeCompare() : 기준 문자열과 비교했을 때 비교 대상 문자열이 정렬상 전에 오는지, 후에 오는지 혹은 같은 순서에 배치되는지를 알려주는 숫자를 리턴.
    같으면 0 빠르면 양수 늦으면 음수
    e.g.
'a'.localeCompare('c'); // -2 or -1 ('a'는 'c'보다 느리므로 음수)
'check'.localeCompare('against');
'a'.localeCompare('a'); // 0
  • String.prototype.lastIndexOf()

그 외

  • 정규표현식
    e.g.
var regex = /^\d{6}$|^\d{4}$/;
return regex.test(s);

\d : 숫자
^ : 앞글자가 무조건 매칭되야함 {숫자}만큼 반복 |: 또는 표시

  • isNaN( ) : not a number인지 판단하는 함수
  • Map.prototype.values() : 각 요소의 value를 가지는 iterator object를 반환 (삽입 순서대로)
profile
고수가 되고 싶은 조빱

0개의 댓글