JS Learning Diary-implicit conversion of related pits and knowledge

Source: Internet
Author: User
Tags comparison table string to number true true

The implicit conversion comparison is not the past in JS, even if a few years of experience of the engineer is also likely to be not familiar with this piece of knowledge. Even if you know to use = = = To avoid stepping on the pit, but other members of the team do not necessarily know that there is such a pit, there are back-end language experience people often form a thinking error: "JS This language is very simple, look at the syntax to find a few examples can operate the DOM, write special effects." With react, Vue, HTML5 and other technologies in the project of large-scale use, more and more projects using a large number of JS, and even the entire project with JS to write (for example, based on the Webapi Spa management background, small programs, H5 applications, Hybrid app), if not to learn JS , without changing the mindset, your program is likely to generate bugs in these places, making it difficult to find bugs. Let's start today's discussion.

Please write down on the paper the following code will output what starts our knowledge of today's summary.

  Console.log (New String (' abc ') ==true)  Console.log ({}==true)  console.log ([]==![])

If your answer is: True true false, then congratulations, you have all answered the wrong, your ideas may be as follows:

1.new string (' 123 ') created is a string, non-empty string is converted to a Boolean value of true,true==true, the result is naturally true

2.{} is a literal object, the object is converted to a Boolean value of True,true==true, and the result is naturally true

3. The right side has! operator, the highest priority, first turn to the right. An array is an object that converts an object to a Boolean result that is true,! The result of [] is false, the expression to be compared becomes []=false, then the array is converted to a Boolean value of True,true==false, and the result is false

Why are you wrong about a problem? If you are very likely to have not mastered the concept of objects in JS, the special rules of NULL, and the conversion rules of the = = operator, the following begins to expand the appropriate knowledge.

First, the variable takes the literal form, the wrapper way, the new way difference

var a= ' xxx ' declares a string type, which is a basic type

var a=string (' abc '), string () is a wrapper class used to convert a parameter to a string type

var a=new String (' abc ') is equivalent to creating an object type when new is used before the function

  var a= ' abc '  Console.log (typeof a)//string  Console.log (typeof string (' abc '))//string  Console.log ( typeof (New String (' abc ')))//object

What types are object types? In addition to the object type created with the new method, the literal object (that is, the {}) array, date, regular expression, Math, function expression, function pointer, are all object types.

Here again involves a easy to mix place, some students say Var a=function () {} and function A () {} I use typeof output is clearly function Ah, you say is the object type? Since a function expression or function declaration is similar, in fact the JS engine does a work behind, the equivalent of invoking the new function (' parameter 1 ', ' Parameter 2 ', ' function body), created with new, must be the object type, As for TypeOf, it is a special case that the function is returned by the functions.

Ii. JavaScript data types

JavaScript has six basic data types: String, Boolean, number, null, undefined, symbol (ES6 newly added), and a complex data type: Object

The basic type and type of object are stored in an inconsistent manner, the underlying type data is stored in the stack (value type), and the object type (reference type) has a pointer (usually a function name) in the stack that points to the data in the heap. Know this knowledge point only know the relevant rules of the = = operator, only to know the shallow copy and deep copy of the pit.

Three, various types of implicit conversion to the Boolean type comparison table
Data type The value converted to true Value converted to False
Boolean True False
String Any non-empty string "" (empty string)
Number Any non-0 numeric value (including infinity) 0 and Nan
Object Any object Null
Undefined Not applicable Undefine

Iv. Logic! Conversion rules

When using this symbol, the data after the operator is first converted to a Boolean type and then reversed, nothing special. This operator has a very classic application.

var A;var b=!! A

The function of this code is that the value of variable B can only be true or false, when a is undefined the value of B is false, otherwise true

Of course, you can also use var b=a | | False to achieve the same effect, I personally prefer the latter.

The rationale behind this is to apply the knowledge of the third big point above, so it is very necessary to understand the implicit conversion firmly.

The rules of equal comparison = =

The comparison operator converts a type to two operands of different types , and then makes a strict comparison. When two operands are objects, JavaScript compares their internal references and is equal only if their references point to the same object (region) in memory, that is, they have the same reference address in the stack memory.

To avoid being misled by some of the summaries seen on the blog, I specifically queried the description of the type conversion rules on the MDN:

    • When you compare numbers and strings, the strings are converted to numeric values. JavaScript attempts to convert numeric literals to values of numeric types.
    • If one of the operands is a Boolean type, the Boolean type is first converted to a numeric type.
    • If an object is compared to a number or string, JavaScript attempts to return the object's default value. The valueof operator attempts to convert an object to its original value (a string or numeric type value) by means of the method, and ToString. If the attempt to convert fails, a run-time error is generated.
    • Note: When and only when compared to the original value, the object is converted to the original value. When all two operands are objects, they are compared as objects and return true only if they refer to the same object.

From the above-mentioned rule of authority, the following conclusions can be drawn:

1. If both sides of the type are inconsistent, but both sides belong to a string, number, Boolean, the first attempt to convert both sides into a numeric type to compare (above 1th, 2 summary)

  var a= ' 123 '  console.log (a==false)  //false, ' 123 ' turns into numbers 123, right turns into numbers is 0, final comparison 123==0

2. If the side is an object type and the other side is string or number (the Boolean type is also converted to numbers), first see if the type of object can be turned into a number, and if it cannot be converted to a number, the string

  var a=new String (123)  Console.log (a==123)//true,a.valueof () The result is the number 123, the final comparison is 123==123

var a={} console.log (a==1)//The above a==1 in the JS interpretation engine is executed as follows://a.valueof () gets not the base type, call A.tostring () to get ' [Object Object] ' [ Object Object] ' ==1;//Both sides of the type do not, left to the digital Nan==1;//false,nan and any type comparison is false

The above two draw a rule, the equality comparison is to turn left and right into number type to compare

3. If both sides are reference types, do not convert, directly compare the memory referenced in the same address.

  Console.log ([]==[])//false, the pointer points to a different address

4.null and undefined do not convert when compared to any other type, that is, the result is always false when compared to other types, but the result of Undefined==null is always true

5.NaN The result of any type comparison is False,nan==nan and false.

Figuring out the rules, the first few questions are particularly simple, and original aim.

  Console.log (New string (' abc ') ==true)  //step1: Turn right into the number  new string (' abc ') ==1  //step2 new String (' abc '). ValueOf () is not a number or a string, and then calls ToString ()  ' [Object Object] ' ==1//step3: string to number  nan==1//false,nan and any type comparison is false
Console.log ({}==true) //step1: The right turns into a number {}==1 //step2 {}.valueof () is not a number or a string, and then calls ToString () ' [ Object Object] ' ==1 //step3: String to number nan==1//false,nan and any type comparison is false
Console.log ([]==![]) step1:! priority is higher than = =, first turn right, [] is object type, turn to Boolean value True,!true is false []==false //STEP2: Turn right to number 0 []==0 // Step3: The left side is an object, valueof is not a character or string, call ToString (), get the empty string ' ==0 //step4: String into a number 0==0//true
Six, greater than or less than the hole of the character

Let's take a look at an example that will surprise you.

Console.log (' < ' 3 ')//true

If your answer is false, then you should see it again, why is it true? Because the string type compares the size, is not the implicit conversion, but the bit to compare the ASCII code , the 1th bit different returns the result, otherwise continues to compare 2nd bit, until a certain difference, the above example JS engine is so to handle

var a= ' all '. charCodeAt (0)//50

var b= ' 3 '. charCodeAt (0)//51

50<51//false

If the left and right sides are variables when comparing sizes, it is advisable to turn them into numbers first to compare them.

Seven, the pit of 0.1+0.2==0,3 false

The answer is not true, is not to hit, JS in two floating-point numbers, if the result is not an integer, then the decimal point after the default there are many bits, here are detailed instructions 0.1 + 0.2 = = 0.30000000000000004 behind

So when we're in a similar scenario, it's best to use (0.1+0.2). toFixed (1) unify the number of decimal places and compare them.

JS Learning Diary-implicit conversion of related pits and knowledge

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.