Javascript type conversion

Source: Internet
Author: User
For JavaScript, variables also have types. Let's look at the following small example:
This is the tested html

< P >
< Input Type = "Text" Name = "Txtval" />
< Input Type = "Button" Name = "Btntest" Value = "Test" Onclick = "Test ();" />
</ P >
< Span ID = "Lbltest" > Test Results </ Span >

Let's take a look at the test method.

Function Test ()
{
VaR Val;
VaR Result;
VaR Str = '';
Val = Document.all.txt Val. value;
Str = 'Test result < BR > ';
Str + = ' 1 + Val = ';
Result =   1 + Val;
Str + = Result;
Str + = ' < BR > 1 + Parseint (VAL) = ';
Result =   1 + Parseint (VAL );
Str + = Result;
Document. All. lbltest. innerhtml = STR;
}

Result Display

Test Results
1 + val = 11
1 + parseint (VAL) = 2

Obviously, Val is a string. Isn't JavaScript automatically converted? Yes! This is for sure. In the above example, if you add Val ++ before all addition operations, the results will be different. New Test Method

Function Test ()
{
VaR Val;
VaR Result;
VaR Str = '';
Val = Document.all.txt Val. value;
Str = 'Test result ';

Val ++ ;
Str + = ' < BR > Val ++ Post Val = '
Str + = Val;

Str + = ' < BR > 1 + Val = ';
Result =   1 + Val;
Str + = Result;

Str + = ' < BR > 1 + Parseint (VAL) = ';
Result =   1 + Parseint (VAL );
Str + = Result;

Document. All. lbltest. innerhtml = STR;
}

New results

Test Results
Val ++ post val = 2
1 + val = 3
1 + parseint (VAL) = 3

sometimes the type conversion is obviously executed to prevent errors.

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.