Home > Web Front-end > JS Tutorial > Common functions and codes for js variable type conversion [comprehensive]_javascript skills

Common functions and codes for js variable type conversion [comprehensive]_javascript skills

WBOY
Release: 2016-05-16 18:40:51
Original
1396 people have browsed it
1. Conversion function:

js provides two conversion functions, parseInt() and parseFloat(). The former converts the value into an integer, and the latter converts the value into a floating point number. Only by calling these methods on the String type can these two functions run correctly; for other types, NaN (Not a Number) is returned.

Both parseInt() and parseFloat() will carefully analyze the string before determining whether it is a numeric value. The parseInt() method first checks the character at position 0 to determine whether it is a valid number; if not, the method will return NaN and will not continue to perform other operations. But if the character is a valid number, the method will look at the character at position 1 and perform the same test. This process will continue until a character that is not a valid number is found, at which time parseInt() will convert the string before the character into a number.

For example, if you want to convert the string "1234blue " into an integer, then parseInt() will return 1234 because when it detects the character b, it will stop the detection process. Numeric literals contained in strings are correctly converted to numbers, so the string "0xA" is correctly converted to the number 10. However, the string "22.5" will be converted to 22 because the decimal point is an invalid character for integers. Some examples are as follows:

parseInt("1234blue"); //returns 1234
parseInt("0xA"); //returns 10
parseInt("22.5"); //returns 22
parseInt("blue"); //returns NaN

The parseInt() method also has a base mode, which can convert binary, octal, hexadecimal or any other base string into an integer. The base is specified by the second parameter of the parseInt() method, so to parse the hexadecimal value, you need to call the parseInt() method as follows:
parseInt("AF", 16); //returns 175
Of course, for binary, octal, or even decimal (default mode), you can call the parseInt() method like this:
parseInt("10", 2); //returns 2
parseInt("10", 8); //returns 8
parseInt("10", 10); //returns 10
If the decimal number contains leading 0s, it is best to use base 10 so that you do not accidentally get an octal value . For example:
parseInt("010"); //returns 8
parseInt("010", 8); //returns 8
parseInt("010", 10); //returns 10
In this code, both lines of code parse the string "010" into a number. The first line of code treats this string as an octal value and parses it in the same way as the second line of code (which declares base 8). The last line of code declares base 10, so iNum3 ends up equaling 10.

The parseFloat() method is similar to the parseInt() method. It looks at each character starting from position 0 until the first non-valid character is found, and then converts the string before the character into number. However, for this method, the first decimal point is a valid character. If there are two decimal points, the second decimal point will be considered invalid, and the parseFloat() method will convert the string before this decimal point into a number. This means that the string "22.34.5" will be parsed as 22.34.
Another difference in using the parseFloat() method is that the string must represent the floating point number in decimal form, not in octal or hexadecimal form. The
method ignores leading 0s, so the octal number 0908 will be parsed as 908. For the hexadecimal number 0xA, the method will return NaN because x is not a valid character in floating point numbers. In addition, parseFloat() has no base mode.

The following is an example of using the parseFloat() method:
parseFloat("1234blue"); //returns 1234.0
parseFloat("0xA"); //returns NaN
parseFloat(" 22.5"); //returns 22.5
parseFloat("22.34.5"); //returns 22.34
parseFloat("0908"); //returns 908
parseFloat("blue"); // returns NaN

2. Forced type conversion

You can also use type casting to process the type of the converted value. Use a cast to access a specific value, even if it is of another type.
The three types of casts available in ECMAScript are as follows:
Boolean(value) - Convert the given value into Boolean type;
Number(value) - Convert the given value into a number (Can be an integer or floating point number);
String(value) - Convert the given value into a string.
Converting a value using one of these three functions will create a new value that stores the value directly converted from the original value. This can have unintended consequences.
The Boolean() function returns true when the value to be converted is a string, non-zero number, or object with at least one character (this will be discussed in the next section). If the value is an empty string, the number 0, undefined, or null, it will return false.

You can use the following code snippet to test Boolean type conversion.

Boolean(""); //false – empty string
Boolean("hi"); //true – non-empty string
Boolean(100); //true – non- zero number
Boolean(null); //false - null
Boolean(0); //false - zero
Boolean(new Object()); //true – object

Number()'s coercion is similar to the parseInt() and parseFloat() methods, except that it converts the entire value rather than part of the value.Remember, the parseInt() and parseFloat() methods only convert the string before the first invalid character, so "4.5.6" will be converted to "4.5". Casting with Number(), "4.5.6" will return NaN because the entire string value cannot be converted to a number. If the string value can be completely converted, Number() will determine whether to call the parseInt() method or the parseFloat() method. The following table illustrates what happens when the Number() method is called on different values:

Usage Result
Number(false) 0
Number(true) 1
Number(undefined) NaN
Number(null) 0
Number( "5.5 ") 5.5
Number( "56 ") 56
Number( "5.6.7 ") NaN
Number(new Object()) NaN
Number(100) 100

The last cast method, String(), is the simplest because it can convert any value into a string. To perform this cast, just call the toString() method on the value passed in as a parameter, which converts 1 to "1", true to "true", false to "false", and so on. analogy. The only difference between casting to a string and calling the toString() method is that casting a null or undefined value produces a string without raising an error:

var s1 = String(null); / /"null"
var oNull = null;
var s2 = oNull.toString(); //won't work, causes an error

3. Use js variable weak type conversion

Give me a small example, you will understand after you look at it.



The above example takes advantage of the weak type characteristics of js and only performs arithmetic operations to achieve type conversion from string to number. However, this method is not recommended. //Convert object to character

function object2String(obj) {
var val, output = "";
if (obj) {
output = "{ ";
for (var i in obj) {
val = obj[i];
switch (typeof val) {
case ("object"):
if (val[0 ]) {
output = i ":" array2String(val) ",";
} else {
output = i ":" object2String(val) ",";
}
break;
case ("string"):
output = i ":'" val "',";
break;
default:
output = i ":" val ", ";
}
}
output = output.substring(0, output.length-1) "}";
}
return output;
}
Convert array to string

function array2String(array) {
var output = "";
if (array) {
output = "[";
for (var i in array) {
val = array[i];
switch (typeof val) {
case ("object"):
if (val[0]) {
output = array2String(val) ",";
} else {
output = object2String(val) ",";
}
break;
case ("string"):
output = "'" encodeURI(val) "',";
break;
default:
output = val ",";
}
}
output = output .substring(0, output.length-1) "]";
}
return output;
}



function string2Object(string) {
eval("var result = " decodeURI(string));
return result;
}



function string2Array(string) {
eval("var result = " decodeURI(string));
return result;
}
Convert date type into string format in js
<script> <BR>var str= '012.345 '; <BR>var x = str-0; <BR>x = x*1; <BR></script>
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template