Javascript type conversion method

Source: Internet
Author: User
Tags floor function

Variables in Javascript also support conversion of free types into applicable (or required) content for ease of use.

Weak JavaScript does not followProgramFrom the actual variable type to the required data type conversion, for example, a very common error, in the browser script, obtain the sum of one numeric variable to be input and another numeric variable from the form control. Because the variable type is a string type in the Form Control (the timing string sequence contains a number) This attempt will add that string to the variable, even if these values happen to be numbers, the result is converted to the string type in the second variable. At last, the variable obtained from the form control is added to the end of the first string.

Convert to boolean type

When the expression is if and other judgment conditions, the type conversion result will be boolean for judgment. These judgments include logical operations such as and (&), or (|) and non (!). The non-operational conversion variable is of the boolean type, and if the variable is of the Boolean Type-True Type. False is returned, and true is returned. Two non-operations will return a value equivalent to the variable converted to the boolean type.
VaR boolvalue = !! X;
This technique will be used later.
Another alternative method is to pass the target as a parameter to the Boolean constructor.
VaR boolvalue = Boolean (X );
(1) When the value type is converted to the boolean type, zero value will become false, and other values will become true. In addition to the special value Nan (not a number), Nan is used to convert other types to numeric types when no meaningful value is returned. Nan always returns false. Whether it is an infinitely large, infinitely small, or finite value, if it is not zero, true is always returned when converted to a Boolean value.
(2) The conversion rules for string types are simple. Conversion from string type to boolean type returns true except for null strings, and return false for null strings.
(3) For other types, undefined and null will return false, and the object and function types will always return true.
This is the most valuable function when you need to determine whether an object is an undefined object. An error occurs if undefined or null is called. When you are not sure about this (usually what Web browsers care about ), Code An error occurs. If judgment must be performed on the object. We recommend that you convert an object to the boolean type as an expression. If false is returned, the object does not exist. If true is returned, the object exists.
If(document.doc umentelement ){
Scrollx = document.doc umentelement. scrollleft;
}
Two non-operations can be used to determine whether the object can be used. Copy code The Code is as follows: var hasdocel = !! Document.doc umentelement;
...
If (hasdocel ){
Scrollx = document.doc umentelement. scrollleft;
}

Convert to string type


Another alternative method is to pass the target as a parameter to the string constructor.

VaR stringvalue = string (X );

Note that the above value 123e-2 has been converted to the string "1.23" because it has been converted from scientific notation to a normal expression. However, the essential numeric type of JavaScript comes from the IEEE Double Precision Floating Point type, which means only limited precision can be stored. Mathematical operation results may only generate approximate values. When they are converted to strings, they may receive unexpected (bad) results. Therefore, you often need to set specific custom functions to obtain acceptable results. This type conversion mechanism is difficult to guarantee normal results.

When an object or function is converted to a string, their tostring method will be called. By default, object. Prototype. tostring and function. Prototype. tostring are executed except that the "tostring" method is overwritten. It is not necessary to convert a function to a string. function. prototype. the tostring method can complete most of the requirements. It will return "host objects" and methods (the object and method depend on different environments, such as DOM elements ).

Convert to numeric type

There are many common methods to convert data to numeric types, especially from string to numeric type. Any mathematical operation method will perform type conversion except addition (+. Therefore, you can convert the string type to the numeric type to operate with a numeric value, such as subtracting zero or multiplying one.

VaR numvalue = stringvalue-0;

/* Or */

VaR numvalue = stringvalue * 1;

/* Or */

VaR numvalue = stringvalue/1;

However, the + (positive) operation can still convert the string type to the numeric type. This method is the fastest because he does not perform any computing operations.

By the way, the opposite number operation-also performs type conversion to make the target the opposite result.

VaR numvalue = (+ stringvalue );

/* This is unnecessary. The arc has been added after the + operation, just to make the code easier to understand and make it clear, this avoids confusion with addition and continuous operations.

+ The (positive) operation is the fastest way to convert the string type to the numeric type. A parameter passed to the number constructor, which performs type conversion and returns a value type.
VaR numvalue = Number (stringvalue );
Number constructor is the slowest type conversion method, but when the speed is not the key, using it can make the code clean.

For other types, objects and functions are always converted to Nan. Undefined and null indicate nothing, but only null is converted to zero. It may be because they are first converted to the Boolean Type before being converted to the numeric type. In the above Article, the result of converting to the boolean type is clear, and converting null to the Boolean Type will return false. It is changed to zero. Almost all of them do not need to be converted to the numeric type. The true significance of their conversion is that to consider some occasional results, to convert a string, these results are returned (or they are returned only after some mathematical operations ).

Parsefloat

For parsefloat parsing a Null String, Nan is returned for parsefloat parsing a Null String because the Null String does not belong to a numeric expression. The index can be parsed. The octal value starting from 0 does not prevent the string from being parsed into a decimal number. The hexadecimal number returns zero because "X" cannot be parsed as a number and the resolution is stopped.

Non-string type conversion to fast conversion, passed as a string to parsefloat. When the type conversion is used as a string, it is not a normal result. The parsing result is Nan, objects, and functions. A custom tostring method may resolve the returned string to a numeric value. This is a special requirement.

Parseint
The parseint function works in a similar way as parsefloat. The difference is that it tries to convert a string to an integer value and can only recognize a few digits as the number symbol.

The parseint function is occasionally used to convert a single-precision floating point value type to an integer type. This conversion is not applicable because it must first be converted from the string type to the single-precision numeric type. In addition, because it produces some errors, it becomes very inefficient. For example, if the value of 2e-200 scientific notation is correct, the return value is zero, but parseint returns 2. In addition, due to JavaScript formatting, numeric values often return some approximate values. For example, if 1/2 + 1/3 + 1/6 = 0.9999999999999999, the approximate value of the result of this expression should be 1, but parseint returns 0.
Math. round, math. ceil and math. floor is suitable for this job. To get the result, the expression will be treated as a 32-bit signed integer. This rule also applies to the following situations.

Note that the math. Round Function executes common rounding functions. 0.4 and 0.5 are ignored, and above are added with 1. The math. Ceil function adds 1 if there is a decimal number. The math. Floor function is ignored regardless of the decimal size. According to the definition of these functions, the parseint method adopts the same processing method as math. Floor for decimal places.

Toint32
Toint32 is a built-in function. It is useful but cannot be called directly like parseint. There are some unusual ways to use it to convert JavaScript variables to values. But it can be used in some limited cases. Bitwise operations, such as bitwise OR (|) and bitwise AND (&) operations, can be converted to the numeric type when using these operations. But they only work in 32-bit signed integer, so we can call the built-in function toint32 to return the converted 32-bit signed integer variable (for type conversion ). The result is like after the parseint function is called, but the result is limited to 32 bits, so they are all numerical values without Nan or infinity. Even if a null value is used for the operation, the returned result is also a numerical value. The toint32 function can be called even if a single-bit operation is used to calculate the result.

Even undefined, objects, and functions are both converted to 0, and Boolean value true is converted to value 1.

author: Brian
Article Source: http://www.cnblogs.com/gaoweipeng

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.