charAt과 index 접근법의 차이

·2022년 11월 4일
0

Javascript

목록 보기
2/16

레벨 2 알고리즘 문제에서는 index로 문자열에 접근하니 계속 오답처리가 되었다.
charAt을 사용하여 접근하니 모든 테스트 케이스가 통과됐다.
이 둘의 차이가 대체 뭐길래...? 란 생각을 갖고 두 접근법의 차이를 찾아보았다!

📌 index 접근법

string[0]

📌 charAt 접근법

string.charAt(0)

📌 차이점

const str = " ";
const words = str.toLowerCase().split(" "); // words = ["", ""];

📍 index 접근

words.map((el) => {
  return el[0].toUpperCase()
});

index 접근을 하는 문자열이 위와 같이 빈 문자열인 경우, word[0]은 undefined가 된다.
따라서 word[0].toUpperCase()를 사용할 경우 에러가 발생하게 된다.

📍 charAt 접근

words.map((el) => {
  return el.charAt(0).toUpperCase()
});

반면, charAt로 접근할 경우 문자열이 빈 문자열이더라도 word.charAt(0)의 결과는 빈문자열("")이 된다.
따라서 index 접근과 달리 에러가 발생하지 않고 빈문자열 그대로 출력된다.

<참고 :
https://thisthat.dev/string-char-at-vs-string-bracket-notation/
https://study-ihl.tistory.com/131 >

profile
개발을 개발새발 열심히➰🐶

0개의 댓글