admin管理员组

文章数量:1317909

I am trying upgrade my javascript programming skills ( or lets say my programming skills period : ) )

so I am trying to understand some semantics :

in the first line what does the "?" mean as well as the minus sign in "-distance"

in the second line what does '+=' or '-=" mean?

 el.css(ref, motion == 'pos' ? -distance : distance)

animation[ref] = (mode == 'show' ? (motion == 'pos' ? '+=' : '-=') : (motion == 'pos' ? '-=' : '+=')) + distance;

thank you

I am trying upgrade my javascript programming skills ( or lets say my programming skills period : ) )

so I am trying to understand some semantics :

in the first line what does the "?" mean as well as the minus sign in "-distance"

in the second line what does '+=' or '-=" mean?

 el.css(ref, motion == 'pos' ? -distance : distance)

animation[ref] = (mode == 'show' ? (motion == 'pos' ? '+=' : '-=') : (motion == 'pos' ? '-=' : '+=')) + distance;

thank you

Share Improve this question asked Jan 27, 2010 at 9:16 salmanesalmane 4,84713 gold badges50 silver badges61 bronze badges 4
  • 1 Want to improve your programming skills? After you undestand what it does, rewrite it in a readable way that will not confuse the next coder. (btw, it looks like utter nonsense - it is playing with +/- of a number, and then subtracts or add it, seems pointless) – Kobi Commented Jan 27, 2010 at 9:22
  • yes, like this, el.css(ref, -1 * ('pos' === motion) * distance), :P (just a joke) – Dan Beam Commented Jan 27, 2010 at 9:27
  • @Dan: you want (1-('pos'===motion)*2)*distance. – kennytm Commented Jan 27, 2010 at 9:29
  • yes, you're right. the readability is so good even I can interpret it, :D – Dan Beam Commented Jan 27, 2010 at 9:32
Add a ment  | 

5 Answers 5

Reset to default 5

a ? b : c means "b if a is true, c otherwise".

-a means a, negated.

a -= b and a += b mean a = a - b and a = a + b respectively. However, in your example these operators aren't actually present in the code, they are just text strings the code is manipulating.

? is the ternary operator

it equals

if( motion == 'pos' ) { return -distance; } else { return distance; } // - is just negating the distance value
  1. (a ? b : c) means "return b if a is true, and return c if a is false."
  2. The minus sign means negation.
  3. The '+=' and '-=' are simply strings.

What you call 'semantics' is actually programming language syntax. It's very basic knowledge that can be acquired easily by googling a bit or looking at Wikipedia.

Here's the JavaScript article on Wikipedia, and here's the answers on your first (conditional operator section), second (Arithmetic) and third (Assignment) questions within the same article. RTFM please.

Here is a link that will answer the ? question (? is a shorthand evaluation operation). http://www.w3schools./JS/js_parisons.asp

+= would be used to increment a value (also shorthand) e.g.

i = i + 1; is the same as i += 1;

the same applies to -=

本文标签: javascript semanticsStack Overflow