TIL 21 | JS replit - 날짜와 시간, math method, 스위치문

dabin *.◟(ˊᗨˋ)◞.*·2021년 8월 20일
0

Javascript

목록 보기
13/25
post-thumbnail

날짜와 시간

날짜 객체 생성 new Date();

var rightNow = new Date(); //실행되는 순간의 현재 시간을 담는다.
console.log(rightNow); //2019-02-18T00:45:06.562Z

Date객체 함수

let rightNow = new Date();
let year = rightNow.getFullYear();
let month = rightNow.getMonth()+1;
let date = rightNow.getDate();
let day = rightNow.getDay();
let currentHour = rightNow.getHours();
let currentMin = rightNow.getMinutes();

getMonth 메서드는 현재 달보다 1 작은 값을 반환 하므로 주의

특정 날짜의 Date

특정 날짜를 매개변수로 넘기면 해당 날짜의 Date를 반환 받는다. 아래와 같이 매개변수를 넘기면 된다.

let date1 = new Date('August 21, 2021 03:24:00');
let date2 = new Date('2021-08-21T03:24:00');
let date3 = new Date(2021, 8, 21);

만 나이 함수

function getWesternAge(birthday) {
  //현재 시간
  const now = new Date();
  const year = now.getFullYear() - birthday.getFullYear();
  
  if (now.getMonth()<=birthday.getMonth() && now.getDate() < birthday.getDate()) {
    return year - 1;
  } else {
    return year
  }
}

생일이 1997/02/19이고, 현재가 2021/1/1~2021/2/18 일 때를 생각해보자. 2021/2/19가 되면 2021-1997=24살이 되지만, 2021/1/1~2021/2/18에 아직 23살임에도 불구하고 24의 값이 나온다. 따라서 조건문으로 now의 month가 birthday의 month보다 작거나 같고, date가 더 작을 때는 변수 year에서 -1을 하도록 했다.
(getMonth는 현재 달보다 1 작은 값을 반환하지만, 비교에 사용했기 때문에 별다른 변화를 주지는 않았다.)

getTime

1970년 1월 1일로부터 얼마만큼의 밀리초가 지났는지 알려준다. 이 숫자로 비교연산을 통해 언제가 더 과거인지 판단이 가능하다.

let rightNow = new Date();
let time = rightNow.getTime();

math method

round 반올림 메서드

console.log(Math.round(2.5)); //3
console.log(Math.round(2.49)); //2
console.log(Math.round(2)); //2
console.log(Math.round(2.82)); //3

ceil 올림 메서드

console.log(Math.ceil(2.5)); //3
console.log(Math.ceil(2.49)); //3
console.log(Math.ceil(2)); //2
console.log(Math.ceil(2.82)); //3

floor 내림 메서드

console.log(Math.floor(2.5)); //2
console.log(Math.floor(2.49)); //2
console.log(Math.floor(2)); //2
console.log(Math.floor(2.82)); //2

random 랜덤 함수

0.0000000000000000에서 0.9999999999999999 사이의 값에서 랜덤수를 제공

let randomNumber = Math.random();
console.log(randomNumber); //0.4473178983556749

랜덤 함수가 필요한 경우는 로또를 생각하면 된다.

var randomNumber = Math.random();
console.log(Math.floor(randomNumber*10));

최소(min), 최대값(max)을 받아 그 사이의 랜덤수를 return 하는 함수

function getRandomNumber (min, max) {
 let random = (Math.random()*(max - min + 1)) + min;
 return random
}
console.log(getRandomNumber(10, 99)) //40.8395253292408
  • Math.floor(Math.random()); : 0
  • Math.floor(Math.random() * 10); : 0~0.99999999..
  • Math.floor(Math.random() * 10); : 0~9
    [더 알아보기] https://hianna.tistory.com/454

스위치문

복수의 if조건문은 switch문으로 바꿀 수 있다. switch문은 특정 변수를 다양한 상황에서 비교할 수 있게 해준다.

문법

하나 이상의 case문, default문은 필수는 아님

switch(x) {
  case 'value1':  // if (x === 'value1')
    ...
    [break]

  case 'value2':  // if (x === 'value2')
    ...
    [break]

  default:
    ...
    [break]
}

case문이 성공하면 해당 case문의 코드가 실행된다. 이 때, break문을 만나거나 switch문이 끝나면 코드 실행이 멈춘다. 일치하는 case문이 없다면, default문이 있는 경우 default문 아래 코드가 실행된다.

주의 : break문이 없는 경우 조건 부합 여부를 따지지 않고 조건이 일치하는 case문 아래의 코드부터 switch문이 끝날 때 까지의 코드가 모두 실행된다.

if문을 switch문으로 변경해보자.

let a = +prompt('a?', '');

if (a == 0) {
  alert( 0 );
}
if (a == 1) {
  alert( 1 );
}

if (a == 2 || a == 3) {
  alert( '2,3' );
}

[정답]

let a = +prompt('a?', '');

switch(a) {
  case 0:
    alert(0);
    break;
  case 1:
    alert(1);
    break;
  case 2: //실행코드 같은 경우 묶기
  case 3:
    alert('2,3');
    break;
}
  

https://ko.javascript.info/switch

profile
모르는것투성이

0개의 댓글