-
"? and :"
Hi,
The following function is a good one to indicate "random movements to all directions"
What I am really after is more examples of the usage of"question mark" and "the semicolon"
as in the example below..Could you please add some comments to the following lines
what for do we use "?" and ":" Or is there any javascript tutorials that describe ":" and "?"
Thanks
function randomdir() {
if (Math.floor(Math.random()*2)) {
(Math.floor(Math.random()*2)) ? xdir='--': xdir='++';} else {
(Math.floor(Math.random()*2)) ? ydir='--': ydir='++';}id2 = setTimeout('randomdir()', 20000);
}
-
Re: "? and :"
That's a shortcut for if...else. But usually, it's not intended for statements but rather assignments.
if(condition) x=something;
else x=something2;
is equivalent to
x=(condition)?something:something2;
edit:
So, the proper way would be
xdir=(Math.floor(Math.random()*2))?'--':'++';
... and the like