Why does (“foo” === new String(“foo”)) evaluate to false in JavaScript?

前端 未结 5 1746
挽巷
挽巷 2020-11-29 19:31

I was going to start using === (triple equals, strict comparison) all the time when comparing string values, but now I find that

\"foo\" === new String(\"fo         


        
5条回答
  •  庸人自扰
    2020-11-29 20:11

    The new word is a criminal here (as usual, may I say)...

    When you use new, you explicitly express your desire to work with object. It might be surprising for you, but this:

    var x = new String('foo');
    var y = new String('foo');
    x === y; 
    

    ... will give you a mighty false. It's simple: compared are not the objects' insides, but the objects' references. And they, of course, are not equal, as two different objects were created.

    What you probably want to use is conversion:

    var x = String('foo');
    var y = String('foo');
    x === y;
    

    ... and that will give you, as expected, true as result, so you can rejoice and prosper with your equal foos forever. )

提交回复
热议问题