js String坑爹的==

來源:互聯網
上載者:User

標籤:style   blog   color   ar   使用   java   sp   div   log   

js的String類型與java的String類型不同,比較的時候不用equals,可以直接用"==".

測試了下,這個"=="好像比較坑爹

 

<script type="text/javascript">    var a=new String("hehe");    var b=new String("hehe");    var c="hehe";    alert("a==c: "+(a==c));//true    alert("b==c: "+(b==c));//true    alert("a==b: "+(a==b));//false    alert("hehe"=="hehe");//true</script>

怎麼能有這麼沒道理的事情?a=c,b=c,但是a竟然不等於b!!!

我的結論是js中的String類型雖然沒有equals方法,但是當String類型對象與另一個String類型的變數相比較的時候,使用的方法與java的equals方法相類似。而當兩個String類型相比較的時候,"=="才與java中的"=="相類似,即比較兩個對象是否是同一個對象。

與之相對應的java代碼,則沒有這種讓人糾結的地方

String a=new String("hehe");        String b=new String("hehe");        String c="hehe";        String d="hehe";        System.out.println("a==b: "+(a==b));//false        System.out.println("a==c: "+(a==c));//false        System.out.println("c==b: "+(c==b));//false        System.out.println("c==d: "+(c==d));//true        System.out.println("a.equals(b): "+(a.equals(b)));//true

java中通過new建立的String對象用"=="相比較的時候,比較的是對象的地址值,而js中,只有當兩個對象都是用new建立的時候,才比較地址值。

js String坑爹的==

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.