Javascript type conversion Method _javascript tips

Source: Internet
Author: User
Tags bitwise first string floor function
Variables in JavaScript also support free type conversions as applicable (or required) content for ease of use.

Weak-type JavaScript does not convert from the actual variable type to the desired data type according to the programmer's wishes, such as a very common error, in the browser script, from the form control to get the user to enter a numeric type of variable and another numeric variable. 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 the value happens to be some number, and the result will be converted to the string type in the second variable. Only the variables obtained from the form control will be added to the end of the first string at the end.

Convert to Boolean type

When the expression is an if and some other judgment, the result of the type conversion will be boolean to be used for judgment. These judgments include logical operations such as with (&&), or (| |), and non (!). The non OP conversion variable is a Bohr type and if the variable is a Bohr-true. Then it will return false, and vice versa will return true. The two-time non operation will return the equivalent of the variable converted to the Boolean type.
var boolvalue =!! X
This technique will be used later.
Another alternative approach is to pass the target as a parameter to the Boolean constructor.
var boolvalue = Boolean (x);
(1) When a numeric type is converted to a Boolean, the value 0 becomes false and the other values become true. Except for a special value Nan (not a number), Nan is used when other types convert to a numeric type when no meaningful value is returned. NaN always returns FALSE. Whether it is infinitely large or infinitely small or a finite number, as long as it is not 0, it always returns true when converted to a Boolean.
(2) The String type conversion rule is simple, and the string type is converted to a Boolean that returns true except for the empty string, and the empty string returns FALSE.
(3) For other types, undefined and null will return false, object and function types always return true.
This is the most valuable feature when you need to determine whether an object is an undefined object. If an undefined variable (undefined or null) is invoked, an error is generated. When these are not certain (usually the Web browser's concern) in order to avoid code errors, you need to have an if judgment on the object. It is recommended that you convert the object as an expression to a wave type, or false to indicate that the object does not exist, or that if true, the object exists.
if (document.documentelement) {
SCROLLX = Document.documentElement.scrollLeft;
}
Two of times the non operation can determine whether the object can be used.
Copy Code code as follows:

var hasdocel =!! Document.documentelement;
...
if (hasdocel) {
SCROLLX = Document.documentElement.scrollLeft;
}

Convert to String type


Another alternative approach is to pass the target as a parameter to the String constructor.

var stringvalue = String (x);

Note that the value 123e-2 above has been converted to the string "1.23" because the scientific notation has been converted to a normal expression. However, the intrinsic numeric type of Javascript is derived from the IEEE Double-precision floating-point type, which means that only limited precision can be stored. Mathematical operation results may only produce approximate values. When they convert to a string, they may receive unexpected (bad) results. Therefore, it is often necessary to set up specific custom functions to achieve acceptable results. This type of conversion mechanism is difficult to ensure normal results.

When an object or function is converted to a string, their toString method is invoked. Object.prototype.toString and Function.prototype.toString are executed by default except that the "toString" method is overridden. To convert a function to a string, it is not necessary to return the result. The Function.prototype.toString method can accomplish most of the need, and it will return "host objects" and methods (this object and method depend on different environments, such as DOM elements).

Convert to numeric type

Converting to numeric types, especially from strings to numeric types, there are many common ways in which any mathematical method of operation performs a type conversion except addition (+). So converting a string type to a numeric type can be made with a numeric operation, such as subtracting 0 or multiplying by one.

var numvalue = stringValue-0;

/* OR/*

var numvalue = stringvalue * 1;

/* OR/*

var numvalue = STRINGVALUE/1;

However, the + (take positive) action can also convert a string type to a numeric type. Because he does not do any calculation, this method is the fastest.

By the way, the reverse operand-also performs a type conversion, making the target the opposite result.

var numvalue = (+stringvalue);

/* This is unnecessary, after the + operation has been added parentheses, just to make the code easier to understand and make it clear to him, especially to avoid confusion with add and continuous operation.


The + (take positive) action is the fastest way to convert a string type to a numeric type. Passed to a parameter of the number constructor, which performs a type conversion and returns a numeric type.
var numvalue = number (stringvalue);
The number constructor is the slowest type conversion method, but when the speed is not the key to consider, use it to make the code clean.

For other types, Objects and functions are always converted to NaN. Undefined and Null also represent nothing, but only null is converted to numeric zero. It may be that they are converted to a wave type before they are converted to a numeric type, and the result of converting to a Bohr type above is clear, and null converting to a Bohr will return false. It will become a numeric zero. They have almost no need to convert to numeric types, and the real meaning of how they convert is that in order to consider some accidental results, to convert a string, the result returns them (or because some mathematical calculations are performed to return them).

parsefloat

Parsing an empty string for parsefloat will return NaN for parsefloat parsing an empty string because the empty string is not part of a numeric expression. Indices can be parsed, and a 0-headed octal does not prevent the string from being parsed into decimal digits. The hexadecimal number returns a zero because "X" cannot be parsed as a number and the resolution is stopped.

Non-string type conversions become quick conversions, passed to parsefloat as a string. When those type conversions are not normal results as strings, the result is nan,objects and functions. There may be a custom toString method return string that will be parsed into a numeric value, which is a special requirement.

parseint
The parseint function works in a similar way to parsefloat, except that it attempts to convert a string to an integer value, identifying only a few symbols that are numbers.

The parseint function is occasionally used as an integral type for converting single-precision floating-point numeric values. This conversion is not applicable because it is first converted from a string type to a single-precision numeric type. In addition, because it produces some errors, it becomes very inefficient, such as the number 2e-200 of this scientific notation correctly returns because it is zero, but parseint returns 2. And because JavaScript is formatted, values often return some approximations. For example, 1/2 + 1/3 + 1/6 = 0.9999999999999999, the approximate result of this expression should be 1, but parseint should return 0.
Math.round,math.ceil and Math.floor, which can get an approximate value, are appropriate for this work, and in order to get results, the expression will be used as a 32-bit signed integer, and the same rule applies to the following situations.

Note The Math.Round function performs a common rounding, 0.4 and a bit will be ignored, 0.5 and above will be added 1. The Math.ceil function adds 1 as long as there is a decimal number. The Math.floor function is ignored regardless of the decimal size. The definition of these functions shows that the parseint method is the same as Math.floor for decimals.

ToInt32
ToInt32 is a built-in function that, while useful, cannot be invoked directly as parseint. There are some unusual ways to convert JavaScript variables to numeric values. But it can be used in a limited number of cases. Bit operations, such as bitwise OR (|) and bitwise AND (&) manipulate values, they can be converted to numeric types when they are used. But they only work in 32-bit signed plastic surgery, so we can return the converted 32-bit signed reshape variable (type conversion) by calling the built-in function ToInt32. The result is like a parseint function call, but the result is limited to 32 bits, so it's all numeric, not NaN or Infinity. Even if the operation is done with a null value, the result returns a numeric value, but the ToInt32 function can be called by using a bitwise operation that does not impress the result.

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

Article Author: Gao Weipeng (Brian)
Article Origin: 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.