반응형
const str = 'hello world';
console.log(str.charAt(4)); // o
console.log(str[4]); // o
'hello world'이라는 String에서 5번째 문자를 찾으려고 str.charAt(4)라고 실행했다.
str[4]로도 동일한 결과가 나온다 왜나하면 String도 Array의 한 종류이기 때문에 대괄호로 특정 값 접근이 가능하다.
str[] VS str.charAt() 차이점 1
const arr = ['1', '2', '3'];
const obj = { name: 'John', age: 12 };
console.log(arr.charAt(1)) // TypeError: arr.charAt is not a function
console.log(obj.charAt(1)) // TypeError: obj.charAt is not a function
charAt() 함수는 String에만 쓸 수 있는 함수이다.
str[] VS str.charAt() 차이점 2
console.log(str.charAt(-1)); //
console.log(str.charAt(100)); //
charAt() 함수 사용 시, 인덱스 범위가 String의 길이 범위를 벗어나도 아무런 아웃풋이 없다.
console.log(str[-1]); // undefined
console.log(str[100]); // undefined
대괄호로 특정 값 접근 시, 인덱스 범위가 String의 길이 범위를 벗어나면 아웃풋이 undefined이다.
반응형
'코딩 > Javascript' 카테고리의 다른 글
자바스크립트 - 배열 혹은 문자열의 #번째 요소의 값 찾는 법 (at() 함수) (0) | 2023.06.28 |
---|---|
자바스크립트 - 특정 문자의 정숫값 확인 방법 (charCodeAt() 함수) (0) | 2023.04.09 |
자바스크립트 - String 대문자 & 소문자로 변환하기 (toUpperCase() & toLowerCase() 함수) (0) | 2023.04.03 |
자바스크립트 - String 표현 시 " (큰 따옴표), ' (작은 따옴표), ` (억음 부호) 공통점 & 차이점 (0) | 2023.03.31 |
자바스크립트 - Boolean false 값 리스트 (0) | 2022.11.21 |