Javascript 0 == '0'. Explain this example

后端 未结 2 1347
自闭症患者
自闭症患者 2021-01-16 22:53

I found thoose examples in another thread but I dont get it.

0 == \'0\'            // true

0 to the left i converted to false(the only num

2条回答
  •  鱼传尺愫
    2021-01-16 23:33

    When you use == JavaScript will try very hard to convert the two things you are trying to compare to the same type. In this case 0 is converted to '0' to do the comparison, which then results in true.

    You can use ===, which will not do any type coercion and is best practice, to get the desired result.

    Equality operator

    The equality operator converts the operands if they are not of the same type, then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the string operand is converted to a number if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

    Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators

    JavaScirpt Table Equality: http://dorey.github.io/JavaScript-Equality-Table/

提交回复
热议问题