Rule instance parsing _javascript techniques for JavaScript type conversions

Source: Internet
Author: User
Tags numeric logical operators numeric value

Type conversions can be divided into implicit conversions and explicit conversions, which are called implicit conversions, which are automatically converted by programs at run time, and explicit conversions are artificially cast on types. JavaScript variables are loosely typed and can store any data type that JavaScript supports, and the types of variables can be dynamically changed at run time. Please see

Cases:

var n = ten;
n = "Hello csser!";
n = {};

In the example above, first declare the n variable and initialize its value to 10 (the integer type), and then the string "Hello csser!" Assign to N, then assign an object to it, and the last n type is the object type. We can see that the type of variable n is dynamic, in actual programming, we recommend not to change the type of variable frequently, because it is not good for debugging.

Because of the dynamic nature of variable types in JavaScript, the concept of type conversion needs to be used in the actual execution of a program. Type conversions can be divided into implicit conversions and explicit conversions, which are called implicit conversions, which are automatically converted by programs at run time, and explicit conversions are artificially cast on types. This article summarizes the type conversions of JavaScript.

Explicit conversions

With manual type conversions, JavaScript provides the following transformation functions:

Convert to Numeric Type: Number (Mix), parseint (String,radix), parsefloat (String)
Convert to String type: toString (Radix), String (Mix)
Convert to Boolean Type: Boolean (Mix)

1, number (mix) function, you can convert any type of parameter mix to a numeric type. The rules are:

1. If this is a Boolean value, True and false are converted to 1 and 0, respectively.

2. If it is a numeric value, return itself.

3. If it is null, return 0.

4. If it is undefined, return nan.

5. If it is a string, follow these rules:

6.

1. If the string contains only digits, convert it to decimal (ignoring leading 0)

2. If the string contains a valid floating-point format, convert it to a floating-point value (ignoring leading 0)

3. If it is an empty string, convert it to 0

4. If the string contains a format other than the above, convert it to Nan

7. If it is an object, the valueof () method of the object is called, and the value returned by the previous rule transformation is converted. If the result of the conversion is Nan, the object's ToString () method is called, and the string value returned in accordance with the preceding rule transformation is repeated.

The following table lists the return values for the object's valueof ():

Object return value
Array The elements of the array are converted to strings, separated by commas, and concatenated together. The operation is the same as the array.tostring and Array.join methods.
Boolean A Boolean value.
Date The time to store is UTC, which is counted in milliseconds from midnight January 1, 1970.
Function The function itself.
Number numeric value.
Object Object itself. This is the default condition.
String The string value.

Here are a few examples of how you can write the correct results:

Number ("Hello csser!"); /nan number ("
0x8"),//8 number
(""),//0 number
("020DD"),//nan number
("070");//70 number
(True );//1

2, parseint (string, radix) function, converts a string to a numeric value of type Integer. It also has certain rules:

1. Ignore the space before the string until the first non-empty character is found

2. If the first character is not a numeric sign or a minus sign, return Nan

3. If the first character is a number, continue parsing until the string parsing is complete or a non-numeric symbol is encountered

4. If the result of the previous resolution begins with 0, it is resolved as octal; If you start with 0x, you parse it as hexadecimal

Object Operation
Array Converts the elements of an Array to a string. The resulting string is separated by commas and is concatenated.
Boolean Returns "true" if the Boolean value is true. Otherwise, returns "false".
Date Returns the literal representation of a date.
Error Returns a string containing the associated error message.
Function Returns a string with the following format, where functionname is the name of the called ToString method function:

function functionname () {[native code]}

Number Returns the text representation of a number.
String Returns the value of a String object.
Default Returns "[Object ObjectName]", where ObjectName is the name of the object type.

5. If the radix parameter is specified, the radix is the base for parsing

Small quiz:

parseint ("Hello csser!"); /nan
parseint ("0x8");//8
parseint ("");//nan parseint (
"020DD");//20 parseint
("070");
//70 parseint ("22.5");//22

3, parsefloat (string) function to convert a string to a numeric value of a floating-point number type.

Its rules are basically the same as parseint, but also somewhat different: the first decimal symbol in a string is valid, and parsefloat ignores all leading 0, and returns an integer value instead of a floating-point value if the string contains a number that can be resolved to an integer.

4, ToString (radix) method. Values of all types except undefined and null have the ToString () method, which acts as a string representation of the object.

5, string (mix) function to convert any type of value to a string, whose rules are:

1. If there is a ToString () method, call the method (without passing the radix parameter) and return the result

2. If it is null, return "NULL"

3. If it is undefined, return to "undefined"

6, Boolean (Mix) function to convert any type of value to a Boolean value.

The following values are converted to False:false, "", 0, NaN, NULL, and undefined, and any remaining values are converted to true.

Implicit conversions

In some cases, even if we do not provide a display transformation, JavaScript will be automatically type converted, mainly:

1. Functions used to detect whether a Non-numeric value: isNaN (Mix)

The isNaN () function, which is tested to find that the function attempts to convert the parameter value by number (), and returns True if the result is non-numeric, or false.

2. Increment decrement operator (including front and back), unary plus or minus symbol operator

These operators apply to values of any data type, and for different types of values, the operator follows the following rules (which, after comparison, are essentially the same as the number () rule):

1. If it is a string that contains a valid numeric character, convert it to a numeric value (the conversion rule is the same number ()), and the string variable becomes a numeric variable when you perform a plus minus 1 operation.

2. If it is a string that does not contain a valid numeric character, set the value of the variable to nan and the string variable into a numeric variable.

3. If it is a Boolean value false, first convert it to 0 and then perform a plus minus 1 operation, Boolean variable programming numeric variable.

4. If this is a Boolean value true, convert it to 1 and then perform a plus minus 1 operation, and the Boolean variable becomes a numeric variable.

5. If it is a floating-point value, perform a plus minus 1 operation.

6. If it is an object, first call the object's valueof () method, and then apply the preceding rule to the return value. If the result is Nan, then the ToString () method is invoked before the preceding rule is applied. The object variable becomes a numeric variable.

Small quiz:

Perform a post increment operation on the following types of values, and what is the result?

"2″, 02DD", "", false, 22.5, + "",-false, +new Date ()

3. Addition Operation operator

The plus operator operator is also used in JavaScript for string connectors, so the rules for the plus operator are divided into two situations:

• If the two action values are numeric, the rules are:

1. If one operand is Nan, the result is Nan

2. If it is infinity+infinity, the result is Infinity

3. If it is-infinity+ (-infinity), the result is-infinity

4. If it is infinity+ (-infinity), the result is Nan

5. If it is +0+ (+0), the result is +0

6. If (-0) + (-0), the result is-0

7. If it is (+0) + (-0), the result is +0

• If an action value is a string, then:

1. If the two action values are strings, stitch them together

2. If only one action value is a string, the additional action value is converted to a string and then stitched together

3. If an operand is an object, a numeric value, or a Boolean value, call the ToString () method to get the string value, and then apply the preceding string rule. For

Undefined and null, respectively, call string () to the string explicitly.

As can be seen, in addition operations, if there is an action value of string type, then another action value is converted to a string, and finally connected.

4. Multiplication and division, minus operator, modulo operator

These operators are for operations, so they have commonality: if one of the action values is not a numeric value, it is implicitly called the number () function for conversion. For detailed rules for each operation, refer to the definition in ECMAScript.

5. Logical operators (!, &&, | | )

Logical NON (! Operator first converts its action value to a Boolean value through the Boolean () function, and then the negation.

The logic and (&&) operator, if an action value is not a Boolean value, follow these rules for conversion:

1. If the first operand is Boolean () converted to true, the second action value is returned, otherwise the first value is returned (not a Boolean () converted value)

2. Returns null if there is an action value of NULL

3. If there is an action value of Nan, return Nan

4. If there is an action value of undefined, return undefined

Logic or (| | operator, if an action value is not a Boolean value, follow these rules:

1. If the first action value is Boolean () converted to false, the second action value is returned, otherwise the first action value is returned (not a Boolean () converted value)

2. Processing rules and logic for undefined, null, and Nan are the same as (&&)

6. Relational operators (<=, >=)

As with the above operator, the action value of the relational operator can also be of any type, so it is also necessary for the system to perform an implicit type conversion when using a non-numeric type to participate in the comparison:

1. If the two action values are numeric, compare the numbers

2. If the two action values are strings, the character encoding values corresponding to the string are compared

3. If only one action value is numeric, the other action value is converted to a numeric value, which is compared

4. If an operand is an object, call the ValueOf () method (if the object does not have a valueof () method to invoke the ToString () method), and the results are obtained according to the preceding

Rule execution Comparison

5. If an action value is a Boolean value, convert it to a numeric value, and then compare

Note: Nan is a very special value that is not equal to any type of value, including itself, and returns false when compared to any type of value.

7. Equality operator (= =)

The equality operator compares the value of an action after an implicit conversion:

1. If an action value is a Boolean value, convert it to a numeric value before comparing it

2. If one action value is a string and the other action value is numeric, the string is converted to a numeric value through the number () function

3. If one action value is an object and the other is not, the valueof () method of the object is invoked, and the resulting result is compared with the preceding rules

4.null and undefined are equal.

5. If one action value is Nan, the equality comparison returns false

6. If two action values are objects, compare whether they point to the same object

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.