JavaScript 3. prompt와 Number 함수

Yura·2021년 10월 19일
0

JavaScript_Basic

목록 보기
3/28
post-thumbnail

prompt와 Number 함수에 대해 배워보자! 🙋‍♀️

prompt

prompt는 사용자로부터 값을 입력받아 출력하는 질의응답 함수이다.

  • 기본 형식
prompt(안내문,기본값);
prompt("키를 입력하세요", 175); //기본값은 안 넣어도 됨

  • 나이 25를 입력받아 저장하는 age 변수를 선언해보자.
let age = prompt("나이를 입력하세요", 30); // age 변수는 prompt로부터 입력받은 값이다.
console.log("age ="+age);

Number

prompt로 입력받은 값은 무조건 '문자열'로 변환되기 때문에
Number 함수를 사용하여 문자열로 변환된 숫자를 실제 숫자열로 다시 변환시킨다.

  • 실제 출력 : 'weight = 4520'
let weight = prompt("몸무게를 입력하세요",45);
console.log("weight ="+(weight+20));
  • Number 사용으로 숫자 변환되어 '65' 출력
let weight = Number(prompt("몸무게를 입력하세요", 45));
console.log("weight ="+(weight+20));
  • 코드간소화 : 재할당
let weight = prompt("몸무게를 입력하세요", 45); //원래대로 작성 후
weight = Number(weight); //변수 weight은 숫자열이다~ 재할당!
console.log("weight ="+(weight+20));

문제) 사각형의 가로와 세로를 변수 width, height로 입력받아 그 사각형의 넓이와 둘레를 구한 후, 각각 변수 area와 circumference에 저장하여 출력하시오.
-출력 : "area="+area / "circumference="+circumference

let width = prompt("width 값을 입력하세요");
let height = prompt("height 값을 입력하세요");

width = Number(width);    //재할당
height = Number(height);

let area = width*height;
let circumference = (width*height)*2;

console.log("area="+area);
console.log("circumference="+circumference);
profile
가치와 의미를 쫓는 개발자 되기✨

0개의 댓글