[개발자되기: 문자열, 반복문, 조건문] Day-3

Kyoorim LEE·2022년 4월 27일
0

조건문

  • 조건문은 어떠한 조건을 판별하는 기준을 만드는 것
  • 조건문에는 반드시 비교연산자(comparison operator)가 필요

비교연산자

  • <, >, <=, >=, ===, !==
    ex)
1 === 1 // true
1 === "1" // false
true === "true" // false
1 == "1" // true
null == undefined // true
  • 비교의 결과는 늘 true/false

Boolean

조건문 형태

if (조건1) {
  // 조건 1이 통과할 경우
} else if (조건2) {
  // 조건 1이 통과하지 않고 조건 2가 통과할 경우
} else {
  // 모든 조건이 통과하지 않는 경우
}

논리 연산자(locigal operator)

  • 두 가지 조건이 한번에 적용되는 경우
  • 유용한 예
    ex)
    학생이면서, 여성일 때 통과 : isStudent && isFemale; (AND연산자)
    학생이거나, 여성일 때 통과 : isStudent || isFemale; (OR연산자)
    학생이 아니면서, 여성일 때 통과: !isStudent && isFemale;
  • 논리 연산자 NOT
    !false // true
    !(3>2) // false
    !undefined // true
    --> undefined는 false로 취급(falsy)
    !"Hello" // false

    --> "Hello"(string)는 true로 취급(truthy)
  • 논리 연산자 OR
    true || true // true
    true || false // true
    false || false // false
  • 논리 연산자 AND
    true && true // true
    true && false // false
    false && false // false
  • 기억해야할 6가지 falsy 값
    if (false)
    if (null)
    if (undefined)
    if (0) --> 0은 보통 off를 의미하므로
    if (NaN)
    if ('') --> 비어있는 string
    --> if문에서 false로 변환되므로 if 구문이 실행되지 않음

    문자열

    문자열 string, 문자 하나는 character (char)

    문자에 접근하기 (문자 한 개씩 가져오기 - 수정은 안됨, read only)

let str = 'CodeStates';
console.log(str[0]); // 'C'
console.log(str[4]); // 'S'
console.log(str[10]); // undefined

+연산자

string 타입과 다른 타입 사이에 + 연산자를 쓰면 string형식으로 강제변환 (toString)

let str1 = 'Code';
let str2 = 'States';
let str3 = '1';
console.log(str1 + str2); // 'CodeStates';
console.log(str3 + 7)' // '17'

길이 (length property)

let str = 'CodeStates';
console.log(str.length); // 10 

해당 인덱스 찾기 str.index(searchValue)

  • arguments: 찾고자 하는 문자열
  • return value: 처음으로 일치하는 index, 찾고자 하는 문자열이 없으면 -1
  • lastIndexOf는 문자열 뒤에서부터 찾음
'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 (끝에서부터 셈)

str.split(seperator)

  • arguments: 분리 기준이 될 문자열
  • return value: 분리된 문자열이 포함된 배열
let str = 'Hello from the other side';
console.log(str.split(' '));
// ['Hello', 'from', 'the', 'other', 'side']

str.substring(start, end)

  • 텍스트의 중간을 똑 떼서 그 부분만 가져오고 싶을 때
  • arguments: 시작 index(n) 끝 index (n-1)
  • return value: 시작과 끝 index 사이의 문자열
let str = 'abcdefghij';
console.log(str.substring(0,3)); // abc
console.log(str.substring(3,0)); // abc
console.log(str.substring(-1,4); // abcd
console.log(str.substring(0,20)); //abcdefghij

str.toLowerCase () / str.toUpperCase()

  • return value: 대, 소문자로 변환된 문자열
console.log('ALPHABET'.toLowerCase()); // 'alphabet'
console.log('alphabet'.toUpperCase()); // 'ALPHABET'
  • 모든 string method는 원본은 변하지 않음!!!! (immutable)

slice()

  • slice()함수는 배열로부터 특정 범위의 복사한 값을 담고있는 새로운 배열을 만드는 데 사용
  • begin부터 end까지(end는 미포함)
console.log('fivespot'.slice(0,3)); // 'fiv'
  • 인자가 한개일 경우 뒤에서부터 자른 값을 리턴
console.log('fivespot'.slice(4)); // 'spot'

substring vs slice

  • slice 는 첫번째 인자가 두번째 인자보다 크면 빈 문자열을 리턴한다. 반면 substring는 절대값의 차이만큼의 문자열을 리턴한다.
    ex)
console.log('fivespot'.slice(3,0)); // undefined
console.log('fivespot'.substring(3,0)); // 'fiv'
  • slice 인자로 음수를 쓸 경우 끝에서부터 잘라낸다 (첫번째 인자로 쓸 것인지, 아님 인자 하나만 쓸 것인지에 따라 앞부분이 남을지 뒷부분이 남을지 결정됨). 반면 substring은 음수값을 0으로 취급한다
console.log('fivespot'.slice(-4)); // 'spot'
console.log('fivespot'.slice(0,-4)); // 'five'

알아두면 좋은 내용

짝수 vs 홀수

if (num % 2 === 0) {
  return true; 
} else {
  return false;
}

문제 다시보기

  1. miniCaculator
  • 문제: 두 개의 수와 기호를 입력받아 알맞게 계산한 값을 리턴해야 합니다.
  • 인자1: num1, 인자2: num2, 인자3: operator (string)
  • 출력: number 타입 리턴
function miniCalculator(num1, num2, operator) {
  // operator 연산자 (+, -, *, /)에 따른 계산식을 리턴한다
  // TODO: 여기에 코드를 작성합니다.
  if (operator === '+') {
    return num1 + num2;
	} else if (operator === '-') {
  	return num1 - num2;
    } else if (operator === "*") {
      return num1 * num2;
    } else if (operator === "/") {
      return num1 / num2;
    }
}
  1. daysInMonth
  • 문제: 특정 달(month)을 입력받아 각 달에 몇 일이 있는지 리턴해야 합니다.
  • 인자 1: month, number 타입의 정수 (1 <= month && month <= 12)
  • 출력: number 타입을 리턴
  • 주의 사항
    월 예시) 1월은 1, 2월은 2... 12월은 12입니다.
    7월과 8월에는 모두 31일이 존재합니다.
    2월 29일은 존재하지 않는다고 가정합니다.
  • 내가 푼 방식
  • 보완할 점: 더 간결하게 쓸 수 있음. month를 1과 12사이로 정했기 때문에 else에서 false가 나오는 경우의 수를 생각할 필요가 없음. specific한 2월달을 먼저 써주고 그 다음 수가 더 적은 30일 리턴 조건을 써주고 나머지를 else로 묶어 주는 것이 더 효율적인 코드작성이 가능함
function daysInMonth(month) {
  // 1,3,5,7,8,10,12월은 31일을 리턴한다
  // 4,6,9,11월은 30일을 리턴한다
  // 2월 28일을 리턴하며 29일은 false로 리턴한다
  // TODO: 여기에 코드를 작성합니다.
  if (month >= 1 && month <= 12) {
    if (month === 1 || month === 3 || month === 5 || month ===7 || month === 8 || month === 10 || month ===12) {
      return 31;
    } else if (month === 4 || month === 6 || month === 9 || month === 11) {
      return 30;
    } else if (month === 2) {
      return 28;
    } else {
      return false;
    }
  }
}
  • 더 나은 풀이
function daysInMonth(month) {
  if (month === 2) {
    return 28;
  } else if (month === 4 || month === 6 || month === 9 || month === 11) {
    return 30;
  } else {
    return 31;
  }
}
  1. makeLastSeenMsg
  • 문제:
    사용자의 이름과 미접속 시간(분)을 입력받아 조건별로 다른 메세지를 리턴해야 합니다.
  • 인자 1 : name // string 타입의 이름
  • 인자 2 : period // number 타입의 미접속 시간 (분 단위)
  • 출력
    string 타입을 리턴해야 합니다.
    미접속 시간이 1시간 보다 적을 경우, 분 단위로 표기합니다.
    미접속 시간이 1시간 보다 크고 24시간 보다 적을 경우, 시간 단위로 내림처리하여 표기합니다.
    미접속 시간이 24시간 보다 클 경우, 일 단위로 내림처리하여 표기합니다.
function makeLastSeenMsg (name, period) {
	let hour = 60;
  	let day = 60 * 24;
  	if (period >= day) {
    	return `${name}: ${Math.floor(period / day)}일 전에 접속함`
    } else if (period >= hour) {
    	return `${name}: ${Math.floor(period / hour)}시간 전에 접속함`
    } else {
      return `${name}; ${period}분 전에 접속함`
    }
}

셀프공부

  • trim
  • 공백문자: 탭문자(\t), Carriage return(\r\n) 및 return 문자(\n)
  • match (advanced)
  • replace (advanced)
  • 정규표현식 (advanced)
profile
oneThing

0개의 댓글