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

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

  从url

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

  中取得iPageNo=12,本来是要跳转到iPageNo+1页,即13页,但实跳上却跳转到了121页,即iPageNo+1的结果是121。

  为什么会这样呢?

  写了下面的测试代码:

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

运行结果是:

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()强制转换一下类型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值