라이브러리

[JAVASCRIPT] str.charAt(index) - 지정된 인덱스의 문자 반환




문자열의 특정 인덱스에 접근하기


JavaScript에서 문자열은 0부터 시작하는 인덱스를 사용하여 접근할 수 있습니다. `str.charAt(index)` 메서드는 문자열의 특정 인덱스에 접근하여 그 인덱스에 위치한 문자를 반환합니다.

# 예제


#hostingforum.kr
javascript

let str = "Hello, World!";

console.log(str.charAt(0)); // H

console.log(str.charAt(7)); // W

console.log(str.charAt(13)); // ! (마지막 인덱스)

console.log(str.charAt(14)); // undefined (인덱스 범위 초과)



# 문자열의 인덱스 범위


문자열의 인덱스는 0부터 시작하여 문자열의 길이까지 범위가 있습니다. 만약 인덱스를 초과하여 접근하려고 하면 `undefined`를 반환합니다.

# 대체 메서드


`str.charAt(index)` 메서드는 `str[index]`와 유사한 동작을 하며, 두 메서드는 모두 문자열의 특정 인덱스에 접근하여 그 인덱스에 위치한 문자를 반환합니다.

#hostingforum.kr
javascript

let str = "Hello, World!";

console.log(str.charAt(0)); // H

console.log(str[0]); // H



# ES6에서 추가된 메서드


ES6에서 추가된 `str[index]` 메서드는 `str.charAt(index)` 메서드와 동일한 동작을 하지만, 더 짧고 간결한 코드를 작성할 수 있습니다.

# 예제


#hostingforum.kr
javascript

let str = "Hello, World!";

console.log(str[0]); // H

console.log(str.charAt(0)); // H



# 결론


`str.charAt(index)` 메서드는 문자열의 특정 인덱스에 접근하여 그 인덱스에 위치한 문자를 반환합니다. 만약 인덱스를 초과하여 접근하려고 하면 `undefined`를 반환합니다. 대체 메서드로 `str[index]`를 사용할 수 있으며, ES6에서 추가된 메서드입니다.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 전체 10,077건 / 1 페이지

검색

게시물 검색