CLASS web

JavaScript

삼항연산자

삼항연산자

앞에서 if문에 대해서 학습했습니다.

2가지의 조건만 사용한다면 그러니까 true false만 사용한다면 삼항연산자만으로도 구현할 수 있습니다.

삼항연산자 사용하기

뭐 간단합니다.

( (조건) ? 조건이 참일 때 실행할 명령문 : 조건이 거짓일 때 실행할 명령문 )

좀 더 자세히 보면..

?다음에는 조건이 참일때 실행할 명령문, : 다음에는 조건이 거짓일 때 실행할 명령문입니다.

 ( 1 == 1) ? "1과 1은 같음" : "다름"; 

그럼 실행해봅시다.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>자바스크립트</title>
<script>
    document.write(( 1 == 1) ? "true" : "false");
</script>
</head>
<body>
</body>
</html>

결과는 바로 아래에서 확인할 수 있습니다.







ternary operator

조건에서 1==1은 이므로 ? 다음의 명령문이 실행됩니다.

다음은 조건이 false인 예제입니다.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>자바스크립트</title>
<script>
    document.write(( 1 == 2) ? "true" : "false");
</script>
</head>
<body>
</body>
</html>

결과는 바로 아래에서 확인할 수 있습니다.







ternary operator



댓글 0개

정렬기준

PinkCoding

PinkCoding

X

PinkCoding

Web Scratch Pad

X

loading

            
            
        

컨텐츠로 돌아가기