Is `if (condition = value)` the correct syntax for comparison?

前端 未结 5 1414
轮回少年
轮回少年 2020-12-12 00:30

If if((hit.transform != transform) means if hit.transform is Not transform, then how do I check if the statement Is correct. if(hit.transfor

相关标签:
5条回答
  • 2020-12-12 00:50

    it's

    if(hit.transform == transform) 
    
    0 讨论(0)
  • 2020-12-12 00:50

    You need to use '==='

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

    0 讨论(0)
  • 2020-12-12 00:52

    Depending on the requirements, you may choose between == and === (negated these will become != 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 comparator 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.

    0 讨论(0)
  • 2020-12-12 01:04
    • != 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.

    0 讨论(0)
  • 2020-12-12 01:12

    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"

    0 讨论(0)
提交回复
热议问题