JavaScript repeat()

데구르르·2023년 10월 31일

코테준비

목록 보기
1/3

코테 문제를 풀다가 몰랐던 메소드를 배우게 되어 적어보는 글.


(출처: 프로그래머스 기초 문제)

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let input = [];

rl.on('line', function (line) {
    input = line.split(' ');
}).on('close', function () {
    str = input[0];
    n = Number(input[1]);
    let answer = str;

    for(let i = 1; i < n; i++) {
        answer += str;
    }
    console.log(answer);

});

나는 그냥 for loop으로 돌려서 제출했는데, 다른 사람의 답을 보니 repeat()이라는 메소드로 한 문장에 끝낸 것을 보았다.

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let input = [];

rl.on('line', function (line) {
    input = line.split(' ');
}).on('close', function () {
    str = input[0];
    n = Number(input[1]);
    console.log(str.repeat(n));
});
/**
     * Returns a String value that is made from count copies appended together. If count is 0,
     * the empty string is returned.
     * @param count number of copies to append
     */
    repeat(count: number): string;

숫자를 인수로 받는 메소드이고, 받은 숫자만큼 반복된 String을 리턴한다.

예시)

let str = "abc"
console.log(str.repeat(3));  //output: abcabcabc

몰랐던 메소드를 알게 된 유익한 하루였다👍

profile
개발 기록

0개의 댓글