From da78a9e329e272dedb2400b79a3bdeebff387d47 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:17 -0500 Subject: initial commit --- .../operators/conditional_operator/index.html | 193 +++++++++++++++++++++ 1 file changed, 193 insertions(+) create mode 100644 files/ko/web/javascript/reference/operators/conditional_operator/index.html (limited to 'files/ko/web/javascript/reference/operators/conditional_operator') diff --git a/files/ko/web/javascript/reference/operators/conditional_operator/index.html b/files/ko/web/javascript/reference/operators/conditional_operator/index.html new file mode 100644 index 0000000000..90f59ea4cd --- /dev/null +++ b/files/ko/web/javascript/reference/operators/conditional_operator/index.html @@ -0,0 +1,193 @@ +--- +title: 삼항 조건 연산자 +slug: Web/JavaScript/Reference/Operators/Conditional_Operator +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Conditional_Operator +--- +
{{jsSidebar("Operators")}}
+ +

조건부 삼항 연산자는 JavaScript에서 세 개의 피연산자를 취할 수 있는 유일한 연산자입니다. 보통 if 명령문의 단축 형태로 쓰입니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-conditionaloperators.html")}}
+ + + +

구문

+ +
condition ? exprIfTrue : exprIfFalse 
+ +

매개변수

+ +
+
condition
+
An expression whose value is used as a condition.
+
exprIfTrue
+
An expression which is evaluated if the condition evaluates to a {{Glossary("truthy")}} value (one which equals or can be converted to true).
+
exprIfFalse
+
An expression which is executed if the condition is {{Glossary("falsy")}} (that is, has a value which can be converted to false).
+
+ +

설명

+ +

condition이 true이면, 연산자는 expr1의 값을 반환하며, 반대의 경우 expr2를 반환한다.

+ +

예제

+ +

여러분이 술을 마실수 있는지 확인할 수 있는 간단한 예제가 여기 있습니다.

+ +
var age = 29;
+var canDrinkAlcohol = (age > 19) ? "True, over 19" : "False, under 19";
+console.log(canDrinkAlcohol); // "True, over 19"
+
+ +

isMember 변수의 값을 기준으로 다른 메시지를 보여주고자 한다면, 다음과 같이 표현할 수 있다.

+ +
"The fee is " + (isMember ? "$2.00" : "$10.00")
+
+ +

또한 다음과 같이 삼항(ternary)의 결과에 따라 변수를 할당할 수도 있다.

+ +
var elvisLives = Math.PI > 4 ? "Yep" : "Nope";
+ +

다음의 예제처럼, 다중 삼항(ternary) 평가도 가능하다(주의: 조건 연산은 우측부터 그룹핑 됩니다.)

+ +
var firstCheck = false,
+    secondCheck = false,
+    access = firstCheck ? "Access denied" : secondCheck ? "Access denied" : "Access granted";
+
+console.log( access ); // logs "Access granted"
+ +

또한 다중 조건 IF 문과 같은 방식으로 여러개의 조건을 사용할 수도 있습니다.

+ +
var condition1 = true,
+    condition2 = false,
+    access = condition1 ? (condition2 ? "true true": "true false") : (condition2 ? "false true" : "false false");
+
+console.log(access); // logs "true false"
+ +

참고 : 괄호는 필수는 아니며 기능에 영향을주지 않습니다. 결과가 어떻게 처리되는지 시각화하는 데 도움이됩니다.

+ +

삼항(ternary) 평가는 다른 연산을 하기 위해 쓸 수도 있습니다.

+ +
var stop = false, age = 16;
+
+age > 18 ? location.assign("continue.html") : stop = true;
+
+ +

하나의 케이스 당 둘 이상의 단일 작업을 수행하려면 쉼표로 구분하고 괄호로 묶으세요.

+ +
var stop = false, age = 23;
+
+age > 18 ? (
+    alert("OK, you can go."),
+    location.assign("continue.html")
+) : (
+    stop = true,
+    alert("Sorry, you are much too young!")
+);
+
+ +

또한, 값을 할당하는 동안 하나 이상의 연산도 가능합니다. 이 경우에, 괄호 안의 값중 마지막 쉼표 (,) 다음의 값이 최종 할당 값이 됩니다.

+ +
var age = 16;
+
+var url = age > 18 ? (
+    alert("OK, you can go."),
+    // alert returns "undefined", but it will be ignored because
+    // isn't the last comma-separated value of the parenthesis
+    "continue.html" // the value to be assigned if age > 18
+) : (
+    alert("You are much too young!"),
+    alert("Sorry :-("),
+    // etc. etc.
+    "stop.html" // the value to be assigned if !(age > 18)
+);
+
+location.assign(url); // "stop.html"
+ + + +

삼항 연산자로 반환하기

+ +

삼항 연산자는 if / else 문을 사용하는 함수를 반환하는 데 적합합니다.

+ +
var func1 = function( .. ) {
+  if (condition1) { return value1 }
+  else { return value2 }
+}
+
+var func2 = function( .. ) {
+  return condition1 ? value1 : value2
+}
+ +

다음과 같이 법적으로 술을 마실수 있는지 여부를 반환하는 함수를 만들수 있습니다.

+ +
function canDrinkAlcohol(age) {
+  return (age > 21) ? "True, over 21" : "False, under 21";
+}
+var output = canDrinkAlcohol(26);
+console.log(output); // "True, over 21"
+ +

if / else 문을 대체하는 삼항연산자가 return을 여러 번 사용하고 if 블록 내부에서 한줄만 나올때 return을 대체 할 수 있는 좋은 방법이됩니다.

+ +

삼항연산자를 여러 행으로 나누고 그 앞에 공백을 사용하면 긴 if / else 문을 매우 깔끔하게 만들 수 있습니다. 이것은 동일한 로직을 표현하지만 코드를 읽기 쉽게 만들어 줍니다.

+ +
var func1 = function( .. ) {
+  if (condition1) { return value1 }
+  else if (condition2) { return value2 }
+  else if (condition3) { return value3 }
+  else { return value4 }
+}
+
+var func2 = function( .. ) {
+  return condition1 ? value1
+       : condition2 ? value2
+       : condition3 ? value3
+       :              value4
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-conditional-operator', 'Conditional Operator')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-conditional-operator', 'Conditional Operator')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-11.12', 'The conditional operator')}}{{Spec2('ES5.1')}}
{{SpecName('ES1', '#sec-11.12', 'The conditional operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.conditional")}}

+ +

같이 보기

+ + -- cgit v1.2.3-54-g00ecf