Rule instance resolution for JavaScript type conversions

Source: Internet
Author: User
Tags logical operators number sign

Http://www.jb51.net/article/79916.htm

Type conversions can be divided into implicit conversions and explicit conversions, so-called implicit conversions, which are automatic conversions by the program at run time, and explicit conversions are artificial casts of types. JavaScript variables are loosely typed and can store any data type supported by JavaScript, and the types of variables can be dynamically changed at run time. Please see below

Cases:

?
123 varn = 10;n = "hello CSSer!";n = {};

In the above example, the n variable is first declared and initialized with a value of 10 (integer type), followed by the string "Hello csser!" Assign a value to N, then assign an object to it, and the last n type is the object type. It can be seen that the type of variable n is dynamic, and in practical programming we do not recommend changing the type of the variable frequently, as this is not good for debugging.

Because of the dynamic nature of the variable types in JavaScript, the concept of type conversion is needed in the course of the program's actual execution. Type conversions can be divided into implicit conversions and explicit conversions, so-called implicit conversions, which are automatic conversions by the program at run time, and explicit conversions are artificial casts of types. This article summarizes the type conversions for JavaScript.

An explicit conversion

By manually converting a type, 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 Boolean, true and False are converted to 1 and 0, respectively

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

3. If NULL, 0 is returned.

4. If it is undefined, return nan.

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

6.

1. If the string contains only numbers, 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 non-above format, convert it to Nan

7. If it is an object, call the object's valueof () method, and then convert the returned value based on the previous rule. If the result of the conversion is Nan, the object's ToString () method is called, and the returned string value is converted again according to the previous rule.

The following table lists the return values of 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 boolean value.
date storage time is from January 1, 1970 The number of milliseconds to start at midnight UTC.
function function itself.
number numeric value.
object the object itself. This is the default condition.
string string value.

Here are a few examples that you can write the correct results for:

?
123456 number ( " Hello csser! " //nan number ( //8 number ( //0 number ( //nan number ( //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 spaces in front of the string until the first non-null character is found

2. If the first character is not a number sign or 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 step parsing starts with 0, it is parsed as an octal, and if it starts with 0x, it is parsed as hexadecimal

Object Operation
Array Converts the element of an Array to a string. The resulting strings are separated by commas and joined together.
Boolean Returns "true" if the Boolean value is true. Otherwise, return "false".
Date Returns the literal representation of the date.
Error Returns a string containing the associated error information.
Function Returns a string in the following format, where functionname is the name of the called ToString method function:

function functionname () {[native code]}

Number Returns the literal 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 you specify the radix parameter, parse with radix as the base

Small quiz:

?
123456 parseint ( " Hello csser! " //nan parseint ( //8 parseint ( //nan parseint ( //20 parseint ( //70 parseint ( //22

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

Its rules are basically the same as parseint, but there is a difference: the first decimal symbol in a string is valid, and parsefloat ignores all leading 0, and if the string contains a number that resolves to an integer, the integer value is returned instead of the floating-point value.

4, ToString (radix) method. Values of all types except undefined and null have the ToString () method, which is the function of returning the string representation of an object.

5, string (mix) function, converts any type of value to a string, the rule is:

1. If there is a ToString () method, call the method (do not pass the radix parameter) and return the result

2. If NULL, returns "NULL"

3. If it is undefined, return "undefined"

6, a Boolean (mix) function that converts any type of value to a Boolean value.

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

Implicit conversions

In some cases, even if we do not provide a display conversion, JavaScript will also perform automatic type conversion, mainly in the following cases:

1. Functions for detecting non-numeric values: IsNaN (Mix)

The IsNaN () function, tested to find that the function attempts to convert the parameter value with number () and returns true if the result is "non-numeric", otherwise false.

2. Increment decrement operator (including front and rear), unary plus sign operator

These operators apply to values of any data type, and for different types of values, the operator follows the following rules (which, by contrast, have the same rules as the number () rule):

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

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 of false, first convert it to 0 and then perform the operation plus minus 1, boolean variable programming numeric variable.

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

5. If it is a floating-point value, perform the 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 called 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, what is the result?

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

3. Addition operator

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

? If the two operation values are numeric, the rule is:

1. If one of the operands 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 it is (-0) + (-0), the result is-0

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

? If there is an action value of string, then:

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

2. If only one action value is a string, convert the additional action value to a string and then stitch it up

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

Undefined and null, respectively, calling string () to be explicitly converted to strings.

As you can see, in an addition operation, if there is an action value of type string, the other action value is converted to a string and finally concatenated.

4. Multiplication, minus operator, modulo operator

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

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

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

Logical AND (&&) operators, if an action value is not a Boolean value, follow these rules to convert:

1. Returns the second action value if the first operand is converted to true after a Boolean (), otherwise returns the first value (not the Boolean () converted value)

2. If there is an action value of NULL, returns 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. Returns the second action value if the first action value is converted to False after a Boolean (), otherwise returns the first action value (not a Boolean () converted value)

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

6. Relational operator (<, <=;, >=)

As with the above operators, the operation values of the relational operators can also be of any type, so it is also necessary for the system to perform implicit type conversions when using non-numeric types to participate in comparisons:

1. If the two operation values are numeric, a numeric comparison

2. If the two action values are strings, compare the character encoding values of the strings

3. If only one operation value is numeric, convert another operation value to a numeric value to compare

4. If an operand is an object, call the ValueOf () method (if the object does not have a valueof () method to call the ToString () method), the resulting results follow the previous

Rule execution Comparison

5. If an action value is a Boolean, 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 it compares size to any type of value.

7. Equality operator (= =)

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

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

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

3. If an action value is an object and the other is not, call the object's valueof () method, and the resulting result is compared with the previous rule

4.null is equal to undefined

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

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

Rule instance resolution for JavaScript type conversions

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.