728x90
#문제
문자열을 입력받아 문자열을 구성하는 각 단어를 요소로 갖는 배열을 리턴해야 합니다.
for , while문은 사용 금지
#예시
let output = getAllWords('Radagast the Brown');
console.log(output); // --> ['Radagast', 'the', 'Brown']
#풀이
const str = "apple banana orange";
const arr = str.split(" ");
document.writeln(arr.length); // 3
document.writeln(arr[0]); // apple
document.writeln(arr[1]); // banana
document.writeln(arr[2]); // orange
*(" ")를 지정하면 문자열을 구분자로 잘라서 각각의 잘라진 조각들을 배열에 저장하여 리턴한다.
const str = "a b c";
const arr = str.split("");
document.writeln(arr.length); // 5
document.writeln(arr[0]); // a
document.writeln(arr[1]); // ' '(space)
document.writeln(arr[2]); // b
document.writeln(arr[3]); // ' '(space)
document.writeln(arr[4]); // c
*("")을전달하면, 문자열을 각각의 문자별로 잘라서 한글자씩(공백포함) 배열에 저장하여 리턴한다.
a b c 같은 경우는 5글자가 되겠다
const str = "apple,banana,orange";
const arr = str.split(",");
document.writeln(arr.length); // 3
document.writeln(arr[0]); // apple
document.writeln(arr[1]); // banana
document.writeln(arr[2]); // orange
* (',')이면 문자열을 ,로 잘라서 만들어진 조각들을 배열에 담아서 리턴한다.
#정답
function getAllWords(str) {
if(str === "") {
return []
}
else {
return str.split(" ")
}
}
★★★ split ★★★
str.split(" ") -> apple banana orange
str.split("") -> a b c
str.split(",") -> apple, banana, orange
728x90
'코플릿 기록 > JavaScript' 카테고리의 다른 글
배열 14번~20번 ★★★ (0) | 2023.01.07 |
---|---|
배열 7번 ★★ (2) | 2023.01.07 |
객체 17번 (0) | 2023.01.01 |
객체 21번 (continue, break) ★★★★ (2) | 2023.01.01 |
객체 18번 (0) | 2023.01.01 |