核心提示:!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Transitional//EN https://www.w3.org/TR/xhtml1/DTD/xhtml1-...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>使用等号运算符比较String对象时需要注意的细节</title> </head> <body> <script> var string1=new String("Confidence"); var string2=new String("Confidence"); document.write(string1==string2); //结果是false document.write("<br/>"); document.write(string1.valueOf()==string2.valueOf()); ///结果是true </script> </body> </html>
因为我们要比较的是两个String对象,而不是两个基本类型的字符串包含的字符。
所以,即使两个字符串对象持有相同的字母,它们也不是同一个对象。
如果你确实需要比较两个对象持有的字符串,可以使用valueOf()方法对数据值进行比较。