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

前端 未结 3 1892
名媛妹妹
名媛妹妹 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: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.

提交回复
热议问题