Type conversion in JavaScript (ii)

Source: Internet
Author: User

Description: This article focuses on the effect of the type conversions of operators on operands in JavaScript, the object types mentioned in this article refer only to JavaScript's predefined types and to the programmer's own implementation of objects, excluding special objects defined by the hosting environment (such as browser-defined objects)

In the previous article, we discussed the conversion of the original type to the original type in JavaScript, the conversion of the original type to the object type, and the conversion of the object type to the original type, which first raises a question

var a = undefined; if (a) {    console.log (' hello ');} Else {    console.log (' World 'false);

When I was not smattering JavaScript, I thought the code above would output ' world ' and ' true ', but after executing the code, we found that the result was ' world ' and ' false '. Undefined can actually be converted to false, However, when using the = = Operator for equality comparisons of undefined and false two values, the type conversion occurs because of the different types of two operands, and undefined is not converted to a Boolean type and then compared with false. So this article discusses the effect of the operator on the operand type conversions.

1.+ (two yuan), ==,!=,>,<,<=,>=

The binary + operator is used to add two numbers or concatenate two strings, so the operator expects the operand type to be a number or a string. When the operands are numbers or strings, the result is obvious, otherwise the operands are now type-converted, the operands are converted to numbers or strings, and then the math is added or the connection string is calculated. The operands are type-converted according to the following rules:

1. If any of the operands is an object type, the conversion of the object to the original type is performed first: for the Date object, the value of the original type is obtained by calling the ToString method, and for other objects, first try the valueof method, and then try the ToString method. If both valueof and ToString cannot get the value of the original type, an exception is thrown

2. Now the two operands are of the original type, and if one of the operands is a string, the operand of the other primitive type is converted to a string and then the string join operation is performed

3. Otherwise, convert two operands to a number for mathematical addition operations

Console.log (' 10 ' +NULL);//10nullConsole.log (' ten ' +undefined);//10undefinedConsole.log (' 10 ' +false);//10falseConsole.log (' 10 ' +true);//10trueConsole.log (' 10 ' +10);//1010        varO1 = {}; Console.log (' Ten ' +o1);//The default valueof method for 10[object object] objects returns not the original type, so the ToString method is calledO1.tostring =function(){            return' O1 '; } console.log (' Ten ' +o1);//10o1O1.valueof =function(){            return NULL; } console.log (' Ten ' +o1);//The 10null object now has a valueof method that returns the original type and no longer calls ToStringconsole.log (10+null);Console.log (10+undefined);//nan, Undefinde converted to number is NanConsole.log (+ +false);//TenConsole.log (+ +true);// One        varO1 = {}; Console.log (10+O1);//The default valueof method for 10[object object] objects returns not the original type, so the ToString method is called, and ToString returns a string, so the string connection is executedO1.tostring =function(){            return true; } console.log (10+O1);// OneO1.valueof =function(){            return NULL; } console.log (10+O1);//The 10 object now has a valueof method that returns the original type, and no longer calls the tostring var date = new Date;Console.log (date +true);//Tue 10:32:49 gmt+0800 (China Standard Time) True

When you use the = = operator to compare the equality of two operands, a type conversion occurs if the two operand types are inconsistent, and the following rules are used for the conversion

1.null and undefined are equal.

2. If one operand is a number and the other operand is a string, convert the string to a number and then compare

3. If there is an operand of type Boolean, convert it to a number

4. If one of the operands is an object type, the object type is converted to the original type and then compared. When converting an object to its original value, the ValueOf method is preferred, followed by the ToString method, but as with the + operator, the Date object is a special case. The Date object calls the ToString method

5. The rest of the situation is considered not to wait

Here you can explain the problems raised in this article, undefined and false = = comparison, false first converted to the number 0, and then compared with undefined, which belongs to the case 5, returns false

Console.log (0 = =NULL);//falseConsole.log (0 = = undefined);//falseConsole.log (0 = =false);//True,false converted to 0Console.log (1 = =true);//True,true converted to 1Console.log (true= = ' 1 ');//True,true First converted to 1, then 1 to string ' 1 'Console.log (NULL= = ' null ');//false, Condition 5        varo = {}; Console.log (o= = ' [Object Object] ';//true,tostring method returns ' [Object Object] 'O.valueof =function(){            return' 1 ';        }; Console.log (true= = O);//true,true First convert to 1,o first call valueof get a raw value ' 1 ', number and string comparison, number converted to string

For the! = operator, the result is always the opposite of the = = operator

For >,< (very cute wood has), <=,>= these four comparison operators, the desired operand type is the same as two Yuan +, either compare two numbers, or compare two strings, if the operand is not full digit or string, then a type conversion will occur, the rule of conversion is as follows:

1. If any of the operands is an object type, try the valueof method and the ToString method to convert the object to the original type, it is important to note that there is no special handling of date here, as with other objects

2. After the first step, the two operands are of the original type, and if they are all strings, string comparisons are made, and if all are numbers, the numbers are compared

3. Otherwise, convert two primitive types to numbers, then compare

Console.log (1 >NULL);//true,null->0Console.log (1 >= undefined);//False,undefined->nanConsole.log (1 <= undefined);//falseConsole.log (NULL> Undefined)//False,null->0,undefinde->nanConsole.log (NULL<= undefined)//falseConsole.log (' 1 ' <true);//false, ' 1 '->1,true->1Console.log (' 1 ' >true);//false        varo = {}; O.tostring=function(){            return10;        }; Console.log (o> 9);//true, o->10Console.log (o > ' 9 ')//true,o->10, ' 9 '->9O.tostring =function(){            return' 10 '; } console.log (o> 9);//true, o-> ' ten ', '->10 'Console.log (o > ' 9 ')//false,o-> ' Ten 'o={}; varo1={}; Console.log (o> O1);//both O and O1 are converted to strings by the ToString method, and the string content is consistentConsole.log (O <O1); Console.log (o>= O1);
2.+ (one Yuan),-(one yuan and two yuan), *,++,--

The operands expected by these operators are numeric types, so when the operands are of the wrong type, the operands are converted to numbers

varA = ' 10 '; Console.log (+A);//+10Console.log (1-A);//-9Console.log (a++);//10, but at this point the type of a has changed, + + and--all need a left value, so + + ' 10 ' is wrongConsole.log (typeofa);//the type of output number,a has changedA = ' 10 '; varo = {}; O.tostring=function() {            return' 10 '; } console.log (o++);//10,o-> '->10Console.log (typeofO);// Numbero = {}; O.tostring=function() {            return' 10 '; } o.valueof=function(){            return false; } console.log (++o);//1, priority to use the ValueOf methodConsole.log (typeofO);// Number
3. Summary

As can be seen from the analysis of this article, most of the operators in JavaScript can only operate on the operands of the primitive type, some of which can only be operated on numeric types, and the other may operate on numbers and string types, and when an operation is performed, the operand is not in accordance with the expected type. The object type is converted to the original type by successive calls to the valueof and ToString methods (note the particularity of the Date object), and then the original type is converted to a number or string.

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.