String and numeric operations in JavaScript

Source: Internet
Author: User
Today, I was hit by the String and numeric + operations in JavaScript. From urlhttp: // www.test.com/test.asp? Ipageno12 is obtained from iPageNo12, which is to jump to the iPageNo + 1 page, that is, 13 pages, but the jump to the 121 page, that is, iPageNo + 1 results in 121.

Today, I was hit by the String and numeric + operations in JavaScript.

From url

Asp? Ipageno = 12 "> http://www.test.com/test.asp? Ipageno = 12

IPageNo = 12 is obtained from iPageNo, which is to jump to the iPageNo + 1 page, that is, 13 pages, but the jump to the 121 page, that is, the result of iPageNo + 1 is 121.

Why?

The following test code is written:

View plaincopy to clipboardprint?

 

The running result is:

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

Visible:

When the String type and the number type are combined, the number type is automatically converted to the String type, and the result is also a String type.
When the String type and the numeric type perform-operation, the String type is automatically converted to the numeric type, and the result is also a numeric type.

Because the iPageNo value obtained from the url is of the String type


IPageNo + 1 = "12" + 1 = "12" + "1" = "121"

Therefore, to obtain numeric data from a Url, use Number () to forcibly convert the type.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.