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

前端 未结 5 1424
轮回少年
轮回少年 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: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.

提交回复
热议问题