Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

ternary operator???... 1

Status
Not open for further replies.

mackey333

Technical User
May 10, 2001
563
US
ok this is a piece of code I found...

Code:
var key = new Array(); 
key['c'] = "content/load/load_database.jsp";
key['o'] = "content/load/load_options.jsp";
key['e'] = "javascript:window.close()";

function getKey(keyStroke) {

	isNetscape=(document.layers);

eventChooser = (isNetscape) ? keyStroke.which : event.keyCode;

Code:
	which = String.fromCharCode(eventChooser).toLowerCase();

	for (var i in key) if (which == i) window.location = key[i];
}
document.onkeypress = getKey;

this script captures key strokes and redirects accordingly...and it works fine but I was just wondering if anyone could explain the bold line. according to refrence book '?:' is called a ternary operator...but in true refrence book fashion there is no explaination to the things you dont understand. i think it is just a complex browser check and uses keystroke.which for netscape and event.keycode for ie, but does anyone know for sure? -Greg :-Q
 
It's also known as the Conditional operator

?: (Conditional operator)
The conditional operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if else statement.Implemented in JavaScript 1.0

Syntax

condition ? expr1 : expr2

Parameters

condition
An expression that evaluates to true or false

expr1, expr2
Expressions with values of any type.

Description

If condition is true, the operator returns the value of expr1; otherwise, it returns the value of expr2. For example, to display a different message based on the value of the isMember variable, you could use this statement:

Code:
document.write ("The fee is " + (isMember ? "$2.00" : "$10.00"))


The code presented above:
eventChooser = (isNetscape) ? keyStroke.which : event.keyCode;

...is an easier way of writing:
if(isNetscape){
eventChooser = keyStroke.which;
}else{
eventChooser = event.keyCode;
}


The main advantage to using Conditional operator is it takes much less code and is easier to modify later. - tleish
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top