문자열 / 조건문(코플릿)
- 문자열: 일상생활에서 확인할 수 있는, 모든 글자의 나열을 문자열
코드와 문자열을 구분하기 위해 작은 따옴표(')나 큰 따옴표(")를 사용하여 문자열을 구분- 문자열은 string, 문자 하나는 character, char이라는 축약어로 표현가능
char가 포함된 메소드도 있음
let str = 'CodeStates';
console.log(str[0]); // 'C'
console.log(str[4]); // 'S'
console.log(str[10]); // undefined
+
연산자를 쓸 수 있음+
연산자를 쓰면 string 형식으로 변환let str1 = 'Code';
let str2 = 'States';
let str3 = '1';
console.log(str1 + str2); // 'CodeStates'
console.log(str3 + 7); // '17'
str1.concat(str2, str3....); 의 형태로도 가능
let str = 'CodeStates';
console.log(str.length); // 10
- argument: 찾고자 하는 문자열
- return value: 처음으로 일치하는 index, 찾고자하는 문자열이 없으면 -1
- lastIndexOf는 문자열 뒤에서 부터 찾음
문자열이 틀리면 -1 두개의 문자열이 동시에 존재하는 string에선 첫번째 문자열
str.includes(searchValue) - Boolean 으로 반환
'Blue Whale'.indexOf('Blue'); // 0
'Blue Whale'.indexOf('blue'); // -1
'Blue Whale'.indexOf('Whale'); // 5
'Blue Whale Whale'.indexOf('Whale'); // 5
'canal'.lastIndexOf('a'); // 3
'Blue Whale'.includes('Blue'); // true
'Blue Whale'.includes('blue'); // false
- arguments: 분리 기준이 될 문자열
- return value: 분리된 문자열이 포함된 배열
- 줄바꿈으로 나뉠때 : str.split('\n')
(csv 형식을 처리할 때 유용)
let str = 'Hello from the other side';
console.log(str.split(' '));
// ['Hello', 'from', 'the', 'other', 'side']
- arguments: 시작 index, 끝 index
- return value: 시작과 끝 index 사이의 문자열
- 음수는 0으로 취급
- 초과하면 index 범위까지
let str = 'abcdefghij';
console.log(str.substring(0, 3)); //'abc'
console.log(str.substring(3, 0)); //'abc'
console.log(str.substring(1, 4)); //'bcd'
console.log(str.substring(-1, 4)); //'abcd'
console.log(str.substring(0, 20)); //'abcdefghij'
str.slice(start, end)
substring 과 비슷하나, 몇가지 차이점을 보임
- arguments: 없음
- 소문자로 바꾸기 / 대문자로 바꾸기
조건문 코플릿에서 새로 배운것
- 짝수 여부 확인
function isEven(num) { if (num % 2 === 0) { return true; } return false; } //num % 2 === 0 임의의 Number를 2로 나눈 나머지가 0과 같다.
- 거듭제곱 만들기
(num * num) //num곱하기 num num ** 2 //num의2승 Math.pow(num,2) //num의2승 수식
- 임의의 값을 입력받아
falsy
값인지 여부를 리턴해야함function isFalsy(anything) { return !Boolean(anything); }
문자열 코플릿에서 새로 배운것
- 올림/ 반올림/ 내림
Math.ceil() //올림 Math.round() //반올림 Math.floor() //내림
- 문자열 3개를 입력받아, 가장 짧은 문자열을 리턴 Reference
function findShortestOfThreeWords(word1, word2, word3) { let shortestWord = word1; // 첫 번 째 글자가 2번째 글자보다 길 때 if (word1.length > word2.length) { shortestWord = word2; // word 2 랑 word 3을 비교 if (word2.length > word3.length) { shortestWord = word3; } } else { // word1 과 word3 을 비교 if (word1.length > word3.length) { shortestWord = word3; } } return shortestWord; }
- 문자열 3개를 입력받아, 가장 짧은 문자열을 리턴 내 생각
function findShortestOfThreeWords(word1, word2, word3) { if (word1.length <= word2.length && word1.length <= word3.length){ return word1; } else if (word2.length <= word3.length) { return word2; } else { return word3; } }
- 두 개의 숫자 문자열을 입력받아 더 큰 수를 나타내는 문자열을 구하고, 해당 문자열이 나타내는 수에 5를 더한 수를 나타내는 숫자 문자열을 리턴
- paraseInt() 문자열 인자를 구문분석하여 특정 진수(수의 진법 체계에 기준이 되는 값)의 정수를 반환
function compareNumberStrings(numStr1, numStr2) { let num1 = parseInt(numStr1); let num2 = parseInt(numStr2); if (num1 > num2) { return String(num1 + 5); } else { return String(num2 + 5); } }
- 표현식
let hour, min, sec;
function showTime(hour, min, sec) {
return `현재 시각은 ${hour}시 ${min}분 ${sec}초 입니다.`
} //string을 만들때 `를 앞뒤로 넣고 표현식을 포함해 문자열을 표현할 때 표현식을 ${}로 넣어준다.
함수를 짜기 전에 수도 코드를 잘 짜야겠다 문제풀기에 급급하지말고 왜 이런 코드를 만들었는지, 내가 만든 코드가 일관성이 있는지, 가독성이 좋은지, 확인하자