admin管理员组

文章数量:1387423

If if((hit.transform != transform) means if hit.transform is Not transform, then how do I check if the statement Is correct. if(hit.transform = transform) doesn't seem to work.

If if((hit.transform != transform) means if hit.transform is Not transform, then how do I check if the statement Is correct. if(hit.transform = transform) doesn't seem to work.

Share Improve this question edited Jan 9, 2012 at 19:46 Andy E 345k86 gold badges481 silver badges451 bronze badges asked Dec 13, 2011 at 1:17 Electricaln00bElectricaln00b 694 bronze badges 1
  • Thanks dudes for the Quick and Lots of answers.. StackOverflow is the best! – Electricaln00b Commented Dec 13, 2011 at 1:24
Add a ment  | 

5 Answers 5

Reset to default 8

You need two equals signs for equality

if (hit.transform == transform)

Note that that will allow all sorts of implicit conversions, so you should really use three equals signs—identity equality or strict equality:

if (hit.transform === transform)

Note that a single equals sign is assignment.

x = y;

Now x has the value of y.

Your statement

if(hit.transform = transform)

Assigns hit.transform to the value of transform, then tests to see if the result of this expression, which will be the same as hit.transform's new value, is "truthy"

Depending on the requirements, you may choose between == and === (negated these will bee != and !== respectively). The triple equal sign notation will also perform type checking.

Try entering the following in your javascript console:

1 ==  1    // true
1 === 1    // true

1 ==  "1"  // true
1 === "1"  // false

Edit: = is the assignment operator, which is different from the above parator operators:

a = 1      // 1
a = "1"    // "1"
a = "foo"  // "foo"

When using this within an if-condition like if(a = "foo") you are effectively setting a to "foo", and then testing if("foo"). While "foo" in itself is not a boolean condition, the Javascript engine will convert it to true, which is why it still works.

This is however likely to introduce very subtle bugs which may be quite hard to trace down, so you'd better avoid programming like this unless you really know what you're doing.

it's

if(hit.transform == transform) 

You need to use '==='

Here is the first result on google with an explanation http://geekswithblogs/brians/archive/2010/07/03/quality-equality-with-javascript-quotquot-gt-quotquot.aspx

  • != is not equal to.
  • == is equal to.

So you'd write:

if (hit.transform == transform) {

What you wrote actually attempts so set the value of hit.transform to transform.

本文标签: javascriptIs if (conditionvalue) the correct syntax for comparisonStack Overflow