본문 바로가기

Algorithm

[coderbyte/js] First Reverse

문제 : 

Have the function FirstReverse(str) take the str parameter being passed and return the string in reversed order. For example: if the input string is "Hello World and Coders" then your program should return the string sredoC dna dlroW olleH.

풀이방법 : 

1. str로 들어오는 string 값을 쪼개서 배열에 담는다

2. 배열을 역순으로

3. join('')으로 배열에서 string으로 변환

 

처음에 str을 쪼개서 배열에 담고 나면 for문을 돌려서 

역순으로 다시 배열에 담아서 출력을 해볼까 생각했었는데 

이런 수고를 덜어주기 위해 존재하는 .reverse()로 좀 더 간결하게 해결 할 수 있었다.

 

 

Array.prototype.reverse() - JavaScript | MDN

reverse() 메서드는 배열의 순서를 반전합니다. 첫 번째 요소는 마지막 요소가 되며 마지막 요소는 첫 번째 요소가 됩니다.

developer.mozilla.org

function FirstReverse(str) { 
  return str.split("").reverse().join('');
}