標籤: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坑爹的==