function solution(my_string) {
return my_string.split('').reverse().join('');
}
-> 깔끔하게 잘 풀었다!
⭐️ string.split( ) : 문자열을 쪼개서 배열에 담아주는 함수.
ex) "hello".split(' ') -> ['h', 'e', 'l', 'l', 'o']
⭐️ array.reverse( ) : 배열 안에 있는 요소의 순서를 뒤집어주는 함수.
ex) ['h', 'e', 'l', 'l', 'o'].reverse( ) -> ['o', 'l', 'l', 'e', 'h']
⭐️ array.join() : 배열을 string으로 바꿔주는 함수.
ex) ['h', 'e', 'l', 'l', 'o'].join(' ') -> 'hello'
형태가 뭔가 다르게 생겨서 처음에 당황했다.
python으로 풀듯이 하려고 했는데 console.log( )로 하니 자꾸 자동 줄바꿈이 되었다.
-> 빈 string을 만들어서 더하는 방식으로 해결했다.
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 () {
let n = Number(input[0]);
for(i=1; i<=n; i++){
let str = "";
for(j=1; j<=i; j++){
str += "*"
}
console.log(str)
}
});
더 간편한 방식으로 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 () {
let n = Number(input[0]);
for(i=1; i<=n; i++){
console.log('*'.repeat(i))
}
});
function solution(num_list) {
var answer = [];
var even = 0;
var odd = 0;
for(i =0; i < num_list.length; i++){
if(num_list[i] % 2 === 0){
even++;
}else{
odd++;
}
}
answer.push(even, odd);
return answer;
// 혹은 return [even,odd];
}
⚠️
return answer.push(even, odd)
push 한 걸 바로 return하면 오류가 생기므로 push 한 후에 array를 return해주어야 한다.
function solution(my_string, n) {
var answer = [];
var arr = my_string.split('');
for(i=0; i<arr.length; i++){
answer.push(arr[i].repeat(n));
}
return answer.join('');
}
깔끔한 방식
function solution(my_string, n) {
return [...my_string].map((item)=> item.repeat(n)).join("");
}
⭐️ string을 쪼개서 array에 넣는 방법
1. string.split(' ')
2. [...string]
: spread operator(...) 를 이용한 방법
⭐️ array.repeat( ) : array 안에 있는 요소 반복하기
ex) array.repeat(n) -> array 안에 있는 요소를 n번 만큼 반복.