JavaScript Tutorial/Operators/Conditional Operator
Содержание
Conditional Operator: ?
<html>
<head>
<title>Conditional Operator Demo</title>
<script language="javascript" type="text/javascript">
<!--
confirmVal = confirm("click");
alertStr = confirmVal ? "You clicked OK": "You clicked Cancel";
alert(alertStr);
//-->
</script>
</head>
<body>
<h1>JavaScript Test Page</h1>
</body>
</html>
Finding the absolute value
<html>
<head>
<title>Finding the absolute value</title>
<script language="javascript" type="text/javascript">
<!--
function f()
{
var myVar = prompt("A number", "");
var theModulus = (myVar>=0)? myVar: -myVar;
var msg = (isNaN(theModulus))? "Numbers only.": "The modulus of " + myVar + " is " + theModulus;
alert(msg);
}
//-->
</script>
</head>
<body>
<h1>Finding the absolute value</h1>
<a href="javascript:f()">Get absolute value</a>
</body>
</html>
Tenary operator
<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
var w = 1, x = 2, y = 3, z = 4, ans;
ans = (w > x) ? y : z
alert(ans);
// -->
</script>
</head>
<body>
</body>
</html>
The Conditional Operator and if Statement
An expression that evaluates to a Boolean is always placed to the left of the question mark (?) in the Conditional Operator.
If the expression evaluates to true, the value between the question mark and the colon (:) is returned.
If the expression evaluates to false, the value following the colon is returned.
<html>
<SCRIPT LANGUAGE="JavaScript">
<!--
mailFlag = "YES"
var message1;
var message2;
if (mailFlag == "YES"){
message1 = "A";
}else{
message1 = "B";
}
//Same statement using conditional operator
message2 = (mailFlag == "YES") ? "A" : "B";
document.write("The if statement returns: ",message1,"<BR>");
document.write("The conditional operator returns: ",message2);
-->
</SCRIPT>
</html>