今天被JavaScript的String型和數字型的+運算撞了一下腰。

來源:互聯網
上載者:User

  今天被JavaScript的String型和數字型的+運算撞了一下腰。

 

  從url

 

http://www.test.com/test.asp?ipageno=12

 

  中取得iPageNo=12,本來是要跳轉到iPageNo+1頁,即13頁,但實跳上卻跳轉到了121頁,即iPageNo+1的結果是121。

 

  為什麼會這樣呢?

 

  寫了下面的測試代碼:

 

<mce:script language="javascript"><!--<br />var iPageNo = "12";<br />document.write("var iPageNo =/"12/";<BR><BR>");<br />var a1= 1 + iPageNo;<br />var a2= iPageNo + 1;<br />var b1= 1 - iPageNo;<br />var b2= iPageNo - 1;<br />document.write("typeof(1 + iPageNo)= " + typeof(a1) + ", 1 + iPageNo = " + a1);<br />document.write("<BR><BR>");<br />document.write("typeof(iPageNo + 1)= " + typeof(a2) + ", iPageNo + 1 = " + a2);<br />document.write("<BR><BR>");<br />document.write("typeof(1 - iPageNo)= " + typeof(b1) + ", 1 - iPageNo = " + b1 );<br />document.write("<BR><BR>");<br />document.write("typeof(iPageNo -1 )= " + typeof(b2) + ", iPageNo - 1 = " + b2);<br />document.write("<BR><BR>");<br />iPageNo = 12;<br />document.write("iPageNo = 12;<BR><BR>");<br />var a1= '1' + iPageNo;<br />var a2= iPageNo + '1';<br />var b1= 1 - iPageNo;<br />var b2= iPageNo - '1';<br />document.write("typeof('1' + iPageNo) = " + typeof(a1) + ", '1' + iPageNo = " + a1);<br />document.write("<BR><BR>");<br />document.write("typeof(iPageNo + '1') = " + typeof(a2) + ", iPageNo + '1' = " + a2);<br />document.write("<BR><BR>");<br />document.write("typeof('1' - iPageNo) = " + typeof(b1) + ", '1' - iPageNo = " + b1);<br />document.write("<BR><BR>");<br />document.write("typeof(iPageNo - '1') = " + typeof(b2) + ", iPageNo - '1' = " + b2);<br />// --></mce:script></p><p>

運行結果是:

 

var iPageNo ="12";

typeof(1 + iPageNo)= string, 1 + iPageNo = 112

typeof(iPageNo + 1)= string, iPageNo + 1 = 121

typeof(1 - iPageNo)= number, 1 - iPageNo = -11

typeof(iPageNo -1 )= number, iPageNo - 1 = 11

iPageNo = 12;

typeof('1' + iPageNo) = string, '1' + iPageNo = 112

typeof(iPageNo + '1') = string, iPageNo + '1' = 121

typeof('1' - iPageNo) = number, '1' - iPageNo = -11

typeof(iPageNo - '1') = number, iPageNo - '1' = 11

 

可見:

 

  當String型和數字型進行+運算時,數字型會自動轉換成String型,結果也是String型。
  當String型和數字型進行-運算時,String型會自動轉換成數字型,結果也是數字型。

 

由於從url中取得的iPageNo值的類型是String,所以

iPageNo + 1 = "12" + 1 = "12" + "1" = "121"

 

 

所以,要從Url中擷取數字型資料,要用Number()強制轉換一下類型。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.