Why does new Number(2) != new String(“2”) in JavaScript

前端 未结 3 1851
名媛妹妹
名媛妹妹 2021-01-18 11:06

The following evaluate to true:

new Number(2) == 2
new String(\"2\") == \"2\"

Obviously, but so do the following:



        
相关标签:
3条回答
  • 2021-01-18 11:47

    What I think == is basically does value comparision.

    In above all situations it's comparing just values. But in this one

    new Number(2) == new String("2")
    

    Both are objects so it doesn't compare values, it tries to compare values of object references. That's why it returns false.

    0 讨论(0)
  • 2021-01-18 11:47

    Just try:

    new Number(2) == new Number(2)
    

    that returns

    false

    and you will have the answer: there are 2 different objects that have 2 different references.

    0 讨论(0)
  • 2021-01-18 11:49

    Because JavaScript has both primitive and object versions of numbers and strings (and booleans). new Number and new String create object versions, and when you use == with object references, you're comparing object references, not values.

    new String(x) and String(x) are fundamentally different things (and that's true with Number as well). With the new operator, you're creating an object. Without the new operator, you're doing type coercion — e.g. String(2) gives you "2" and Number("2") gives you 2.

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