今天被JavaScript的String型和数字型的+运算撞了一下腰。
从url
http://www.nigeriaembassy.cn/test.asp?ipageno=12
中取得iPageNo=12,本来是要跳转到iPageNo+1页,即13页,但实跳上却跳转到了121页,即iPageNo+1的结果是121。
为什么会这样呢?
写了下面的测试代码:
运行结果是:
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()强制转换一下类型。