JS variable type conversion common functions and codes [compare full]_javascript techniques

Source: Internet
Author: User
Tags eval getdate numeric value string format string to number type casting
1. Conversion function:

JS provides the parseint () and parsefloat () two conversion functions. The former converts the value to an integer, and the latter converts the value to a floating-point number. These methods are invoked only on the string type, and the two functions are run correctly, and all other types are returned as Nan (not a number).

parseint () and parsefloat () parse the string carefully before deciding whether the string is a numeric value. The parseint () method first looks at the character at position 0 to determine whether it is a valid number, and if not, the method returns Nan and does not continue with other operations. However, if the character is a valid number, the method will look at the characters at position 1 and do the same test. This process continues until a character is found that is not a valid number, at which point parseint () converts the string before the character to a number.

For example, if you want to convert the string "1234blue" to an integer, then parseint () will return 1234, because when it detects character B, it stops the detection process. The literal number contained in the string is converted to numbers correctly, so the string "0xA" is correctly converted to Number 10. However, the string "22.5" will be converted to 22 because the decimal point is an invalid character for an integer. 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 pattern that converts binary, octal, hexadecimal, or any other string of strings into integers. The base is specified by the second parameter of the parseint () method, so to parse the hexadecimal value, you 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:
parseint ("10", 2); Returns 2
parseint ("10", 8); Returns 8
parseint ("10", 10); Returns 10
If the decimal number contains a leading 0, it is best to use cardinality 10 so that you do not accidentally get the octal value. For example:
parseint ("010"); Returns 8
parseint ("010", 8); Returns 8
parseint ("010", 10); Returns 10
In this code, two lines of code parse the string "010" into a number. The first line of code regards this string as a octal value, parsing it in the same way as the second line of code (the Declaration cardinality is 8). The last line of code declares a cardinality of 10, so the iNum3 finally equals 10.

The Parsefloat () method is similar to the parseint () method, viewing each character starting at position 0 until the first inactive character is found, and then converting the string before the character to a number. However, for this method, the first decimal point that appears is a valid character. If you have two decimal points, the second decimal point will be considered invalid, and the Parsefloat () method converts the string before the decimal point to a number. This means that the string "22.34.5" will be parsed into 22.34.
Another difference between using the Parsefloat () method is that the string must represent a floating-point number in decimal form, not in octal or hexadecimal form. The
Method ignores leading 0, so the octal number 0908 will be resolved to 908. For hexadecimal 0xA, the method returns Nan, because x is not a valid character in a floating-point number. In addition, parsefloat () also 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. Force type Conversions

You can also use coercion type conversion (type casting) to handle the type of the converted value. You can use coercion type conversions to access a specific value, even if it is of another type.
The 3 mandatory type conversions available in ECMAScript are as follows:
Boolean (value)--converts a given value to a Boolean;
Number (value)-Converts a given value to a digit (can be an integer or floating point);
String (value)--converts the given value to a string.
Converting a value with one of these three functions creates a new value that holds 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 with at least one character, a number other than 0 digits, or an object (which is discussed in the next section). If the value is an empty string, number 0, undefined, or null, it returns FALSE.

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

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

The force type conversion of number () is similar to the parseint () and parsefloat () methods, except that it converts the entire value, not the partial value. Remember, the parseint () and parsefloat () methods only convert the string before the first invalid character, so "4.5.6" is converted to "4.5". Force type conversion with number (), and "4.5.6" returns Nan, because the entire string value cannot be converted to numbers. If the string value can be completely converted, number () will determine whether to call the parseint () method or call the Parsefloat () method. The following table describes what happens when you call the number () method on a different value:

Usage results
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 force type conversion method string () is the simplest because it converts any value to a string. To perform this coercion type conversion, you only need to call the ToString () method of the value passed in as a parameter, that is, convert 1 to "1", convert True to "true", convert false to "false", and so on. The only difference between casting to a string and invoking the ToString () method is to force a type conversion on a null or undefined value to generate 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. Using JS variable weak type conversion

For a small example, a look, you will understand.
<script>
var str= ' 012.345 ';
var x = str-0;
x = x*1;
</script>

The above example uses the characteristics of the weak type of JS, only arithmetic operation, realize the type conversion of string to number, but this method is still not recommended.
//Object conversion 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 + + + ":" + val + ",";
}
}
Output = output.substring (0, output.length-1) + "}";
}
return output;
}

array into a 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 to string format in JS

<script language= "JavaScript" >
e///////////////////////
Get the current date, format YYYY-MM-DD
////////////////////////////////////////////////////////
function Getcurrentdate ()
{
var year=0;
var month=0;
var day=0;
var currentdate = new Date ();
Return changedatetostring (currentdate);
}

e///////////////////////
Get the current date, format Yyyy-mm-dd hh:mm
////////////////////////////////////////////////////////
function GetCurrentTime ()
{
var year=0;
var month=0;
var day=0;
var currentdate = new Date ();
Return changetimetostring (currentdate);
}

////////////////////////////////////////////////////////
Converts a date type to a string format YYYY-MM-DD
////////////////////////////////////////////////////////
function changedatetostring (Datein)
{
var year=0;
var month=0;
var day=0;
var currentdate= "";
Initialization time
Year = Datein.getyear ();
Month = Datein.getmonth () +1;
Day = Datein.getdate ();

currentdate = year + "-";
if (Month >= 10)
{
currentdate = currentdate + Month + "-";
}
Else
{
currentdate = currentdate + "0" + Month + "-";
}
if (Day >= 10)
{
currentdate = currentdate + day;
}
Else
{
currentdate = currentdate + "0" + day;
}

return currentdate;
}
///////////////////////////////////////////////////////
Converts a date type to a string format Yyyy-mm-dd hh:mm
////////////////////////////////////////////////////////
function changetimetostring (Datein)
{
var year=0;
var month=0;
var day=0;
var Hour = 0;
var Minute = 0;
var currentdate= "";
Initialization time
Year = Datein.getyear ();
Month = Datein.getmonth () +1;
Day = Datein.getdate ();
Hour = Datein.gethours ();
Minute = Datein.getminutes ();

currentdate = year + "-";
if (Month >= 10)
{
currentdate = currentdate + Month + "-";
}
Else
{
currentdate = currentdate + "0" + Month + "-";
}
if (Day >= 10)
{
currentdate = currentdate + day;
}
Else
{
currentdate = currentdate + "0" + day;
}
if (Hour >=10)
{
currentdate = currentdate + "" + Hour;
}
Else
{
currentdate = currentdate + "0" + Hour;
}
if (Minute >=10)
{
currentdate = currentdate + ":" + Minute;
}
Else
{
currentdate = currentdate + ": 0" + Minute;
}
return currentdate;
}
</script>

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.