Difference between test expressions

时间:2015-04-23 05:24:45

标签: javascript

I'm implementing obligatory slider in my project. And the following code worked fine:

else if( current - 1 === sliderLength ){
  current = 1;
  loc = 0
}

But this didn't work as expected:

else if( current === sliderLength - 1 ){
  current = 1;
  loc = 0
}

So, what is difference between current === sliderLength - 1 and current - 1 === sliderLength ?

4 个答案:

答案 0 :(得分:2)

I will rename your variable to x and y for brevity, and just include the pertinent part:

if (x - 1 === y) vs if (x === y - 1)

If you have a hard time seeing the difference, just try them both out for some random values for x and y. Let's try x = 3, y = 2

So, the first one becomes:

if (3 - 1 === 2), or if ((3 - 1) === 2), or if (2 === 2) (i.e. true)

Second one becomes:

if (3 === 2 - 1), or if (3 === (2 - 1)), or if (3 === 1) (i.e. false)

The important thing to note is that the comparison operation (===) happens after the subtraction operation. Actually that's not even that important in this case, but something to note.

答案 1 :(得分:1)

let's take current = 6 and slider=5

Let's take an example

current - 1 === sliderLength  // 5 === 5  ; true statement

current === sliderLength - 1 // 6 ===4  ; that's a false statement

答案 2 :(得分:0)

wrap in math, (evaluate(nest))

else if( current === (sliderLength - 1) ){
  current = 1;
  loc = 0
}

or

else if( (current - 1) === sliderLength ){
  current = 1;
  loc = 0
}

Also consider data typing http://www.w3schools.com/js/js_datatypes.asp

compare http://www.w3schools.com/js/js_comparisons.asp

math () vs eval() http://www.w3schools.com/jsref/jsref_eval.asp

答案 3 :(得分:0)

试试这个:

else if( current === sliderLength + 1 ){
  current = 1;
  loc = 0
}