카테고리 없음
JS 화살표 함수
Canyi
2022. 11. 9. 11:16
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//화살표 함수
//1. function 키워드 제거
//2. 함수의 이름을 변수로 사용
function plus (a,b)
{
return a + b;
}
console.log(plus(10,20));
</script>
</body>
</html>
화살표 함수로 변경
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//화살표 함수
//1. function 키워드 제거
//2. 함수의 이름을 변수로 사용
const plus = (a,b) =>
{
return a + b;
}
console.log(plus(10,20));
</script>
</body>
</html>
화살표 함수 간소화 (구현이 한줄이면서 return 일떄)
const plus = (a,b) => a+b; //바로 값을 return하고 싶을때
인수가 한개일 경우
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//인수가 한개인 경우
const plus = num => num * 2;
alert(plus(100));
</script>
</body>
</html>
인수가 한개도 없을 경우
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//인수가 한개도 없을 경우
const plus = () => alert("더할 데이터가 없습니다."); //undeifnd나오는 이유는 alert의 return값을 목찾음
alert(plus());
</script>
</body>
</html>
undeifnd나오는 이유는 alert의 return값을 못찾음....
화살표 함수를 동적으로 생성 (함수로 작성할 경)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let age =prompt ("나이 입력 : ", 20);
let welcome = (age <= 19)?
function () {
alert("구매할 수 없습니다.");
}:
function () {
alert("구매 가능합니다.");
}
welcome();
</script>
</body>
</html>
화살표 함수로 마이그레이션
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let age =prompt ("나이 입력 : ", 20);
const welcome = (age <= 19)?
()=> alert("구매할 수 없습니다."):
()=> alert("구매 가능합니다.");
welcome();
</script>
</body>
</html>