자바스크립트

[JavaScript] 프로그래머스 문자 반복 출력하기

코딩하는둥이 2023. 7. 18. 13:45

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


문제 설명

문자열 my_string과 정수 n이 매개변수로 주어질 때, my_string에 들어있는 각 문자를 n만큼 반복한 문자열을 return 하도록 solution 함수를 완성해보세요.

 

입출력 예

my_string n result
"hello" 3 "hhheeelllooo"

 

코드 

function solution(my_string, n) {
  const characters = my_string.split('');
  
  const result = characters.map((char) => {
    return char.repeat(n);
  });

  return result.join('');
}

 

다른 예시

function solution(my_string, n) {
    var answer = [...my_string].map(v => v.repeat(n)).join("");
    console.log(answer);
    return answer;
}​
function solution(my_string, n) {
    return my_string.split('').reduce((acc, cur) => acc + cur.repeat(n), '')
}

 

공부

split

 : 문자열을 일정한 구분자로 잘라서 배열로 저장합니다. 

 

1) 파라미터를 입력하지 않은 경우 

   : 문자열 전체 길이가 1인 배열에 담아 리턴합니다.

const str = "a b c";

const arr = str.split();

document.writeln(arr); // a b c
document.writeln(arr.length); // 1

 

2) 단어별로 잘라서 배열에 담기

 : 문자열을 구분자로 잘라 각각의 잘라진 조작들을 배열에 저장하여 리턴합니다.

const arr = str.split(" ");

document.writeln(arr.length); // 3
document.writeln(arr[0]); // a
document.writeln(arr[1]); // b
document.writeln(arr[2]); // c

3) 글자 별로 배열에 담기

 : 문자열을 각각의 문자별로 잘라, 한 글자씩 배열에 저장합니다.(공백포함)

const str = "a b c";

const arr = str.split("");

document.writeln(arr.length); // 5
document.writeln(arr[0]); // a
document.writeln(arr[1]); // ' '
document.writeln(arr[2]); // b
document.writeln(arr[3]); // ' '
document.writeln(arr[4]); // c

4) 특정 구분자로 잘라서 배열에 담기

  : 문자열을 separator로 잘라 만들어진 조각들을 배열에 담아서 리턴합니다.

const str = "a,b,c";

const arr = str.split(",");

document.writeln(arr.length); // 3
document.writeln(arr[0]); // a
document.writeln(arr[1]); // b
document.writeln(arr[2]); // c

5) limit 값 지정하기

 : limit 값을 2로 지정했기 때문에 2개의 배열만 생성됩니다. 

const str = "a,b,c";

const arr = str.split(",", 2);

document.writeln(arr.length); // 2
document.writeln(arr[0]); // a
document.writeln(arr[1]); // b
document.writeln(arr[2]); // undefined

map

 : 배열의 각 요소에 대해 주어진 콜백 함수를 호출하고, 각 콜백 함수의 반환값으로 새로운 배열을 생성합니다. 

const newArray = array.map((currentValue, index, array) => {
  // array: map 메소드가 호출된 배열
  // currentValue: 현재 순회 중인 요소의 값
  // index (optional): 현재 순회 중인 요소의 인덱스
array (optional): map 메소드가 호출된 배열
});
const animal = ["elephant", "Donkey", "tiger", "lion", "monkey"];
const Zoo = animals.map(pet => '😂${pet}');

console.log(Zoo);

// 😂 elephant,😂 Donkey,😂 tiger,😂 lion,😂 monkey


const animal = ["elephant", "Donkey", "tiger", "lion", "monkey"];
const addemoticon = (pet) => '😂${pet}'
const Zoo = animals.map(pet => addemoticon);

console.log(Zoo);

// 😂 elephant,😂 Donkey,😂 tiger,😂 lion,😂 monkey

const animal = ["elephant", "Donkey", "tiger", "lion", "monkey"];
const Zoo = animals.map(pet, index => '${index} ${pet}');


console.log(Zoo);

// 0 elephant,1 Donkey,2 tiger,3 lion,4 monkey