저장을 습관화

자바스크립트 메소드 .repeat() 문자열 반복 본문

공부/JavaScript

자바스크립트 메소드 .repeat() 문자열 반복

ctrs 2023. 9. 7. 12:39

자바스크립트 메소드 .repeat()

주어진 문자열을 옵션의 count만큼 반복하여 붙여 새로운 문자열로 반환한다.

 

예시)

let ex = "Roger";
console.log(ex.repeat(2));

let 안녕로봇 = "안녕!";
const 소환대사 = 안녕로봇.repeat(3)
console.log(소환대사)

실행 결과

 

단, .repeat()은 문자열(string)의 메소드이기 때문에

이외의 데이터 타입 숫자(number), 객체(object), 배열(array) 등에서는 직접 사용할 수 없다.

 

예시)

let a = 123;
console.log(a.repeat(3));

 

실행 결과

$ node test.js
C:\(생략)\test\test.js:2
console.log(a.repeat(3));
              ^

TypeError: a.repeat is not a function
    at Object.<anonymous> ?[90m(C:\(생략)\test\?[39mtest.js:2:15?[90m)?[39m
?[90m    at Module._compile (node:internal/modules/cjs/loader:1254:14)?[39m
?[90m    at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)?[39m
?[90m    at Module.load (node:internal/modules/cjs/loader:1117:32)?[39m
?[90m    at Module._load (node:internal/modules/cjs/loader:958:12)?[39m
?[90m    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)?[39m
?[90m    at node:internal/main/run_main_module:23:47?[39m

Node.js v18.16.0

 

a.repeat은 함수가 아니라는 타입 에러가 발생한다.

 

 

[참조]

https://ctrs.tistory.com/188

 

프로그래머스 LV.0 문자열 반복해서 출력하기

프로그래머스 LV.0 문자열 반복해서 출력하기 https://school.programmers.co.kr/learn/courses/30/lessons/181950 프로그래머스 코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형

ctrs.tistory.com

https://redcow77.tistory.com/629

 

[Javascript] 문자열 일정하게 반복하기 - repeat() 함수

자바스크립트(Javascript)의 repeat() 함수 자바스크립트(Javascript)의 repeat() 함수는 주어진 문자열을 옵션의 count 만큼 반복하여 붙인 다음에 새로운 문자열로 반환하는 함수입니다. 문자열을 반복한

redcow77.tistory.com