Write before the beginning: record the learning bit, if there is any mistake or supplement, I hope you correct me.

Js data type

Js data types: null, undefined, String, Number, Boolean, Symbol, Object, where

Primitive types: Number, String, Null, Undefined, Boolean

Reference type: Object, including Array

JavaScript is a weakly typed or dynamic language. This means that you don’t have to declare the type of the variable in advance; the type will be determined automatically as the program runs. This also means that you can use the same variable to hold different types of data.

Common implicit conversion scenarios

We often encounter the following scenarios during development:

  • ifIn the judgment
    if(XXX){
        ...
    }
Copy the code

This is where the implicit conversion occurs. We know that the if criterion is Boolean, and js converts XXX to Boolean when the code executes to the if criterion.

  • Comparison operator"= ="
[] = = [] / /false{} = = {} / /false[]! / / = []true
Copy the code

If you’re confused by these comparisons, don’t worry, I’ll explain them later.

  • A plus sign"+"With a minus sign"-"
var add = 1 + 2 + '3'
console.log(add);  //'33'

var minus = 3 - trueconsole.log(minus); / / 2Copy the code

As you can see, in some cases + is used as the plus operator, in other cases + is used as a string concatenator, and true is converted to Number with a value of 1, which is subtracted to get 2.

  • .The dot operator
var a = 2;
console.log(a.toString()); // '2';

var b = 'zhang';
console.log(b.valueOf()); //'zhang';

Copy the code

By default, a number or string is converted to an object when a dot operation is invoked on a number or string.

  • When the relational operator is compared
3 > 4 / /false
"2"10 / / >false
"2" > "10"  // true

Copy the code

If both sides of the comparison operator are numeric types, the size is directly compared. If a non-numeric comparison is made, it is converted to a number and then when comparing, if the values on both sides of the symbol are strings, it is not converted to a number for comparison, but the Unicode encoding of the characters in the string is compared separately.

Before we get there, we need to know a few things about valueOf() and toString methods.

  • toString()andvalueOf()These are methods of objects
  • toString()Returns a string, andvalueOf()The original object is returned
  • undefinedandnullThere is notoString()andvalueOf()methods
  • Object wrappervalueOf()Method returns the original value corresponding to the wrapper object
  • usetoString()Methods can distinguish between built-in and custom functions

You can practice the use of these two methods and differences, other specific differences and features are no longer detailed ~

So let’s talk about how data types are converted to each other.

String, Boolean, Number, conversion between objects

1. Change other types to strings

  • Null: to"null".
  • Undefined: to"undefined".
  • Boolean:trueto"true".falseto"false".
  • Number:11to"11"Scientific counting11e20to"1.1 e+21".
  • Array: Empty array[]Convert to an empty string""If the element in the array hasnullorundefined, also treated as an empty string,[1, 2, 3, 4]to"1, 2, 3, 4", which is equivalent to calling the join method of the array, placing each element with a comma","Spliced together.
  • Function:function a(){}Converting to a string is"function a(){}".
  • Generic object: equivalent to calling the object’s toString() method, returns"[object,object]".

    String(null)  // "null"
    String(undefined) // "undefined"
    String(true) / /"true"
    String(false) / /"false"
    String(11)  // "11"
    String(11e20)  // "1.1 e+21"
    String([])  // ""
    String([1,null,2,undefined,3])  // 1,,2,,3
    String(function a/ / () {})"function a(){}"
    String({})  // "[object,object]"
    String({name:'zhang'/ /})"[object,object]"
    
Copy the code

2. Convert other types to Boolean types

Only null, undefined, 0, false, NaN, and empty string cases are converted to Boolean value false, the rest are true, as shown in the following example


    Boolean(null)  // false
    Boolean(undefined)  // false
    Boolean(0)  // false
    Boolean(false) / /false
    Boolean("false") / /true
    Boolean(NaN)  // false
    Boolean("") / /false
    Boolean([])  // true
    Boolean({})  // true
    
Copy the code

3. Change other types to Number

  • Null: to0.
  • Undefined: toNaN.
  • Boolean:trueto1.falseto0.
  • String: If the string is a pure number, it is converted to the corresponding number, for example11to"11"."1.1 e+21"to1.1 e+21.An empty stringto0, and the other cases areNaN.
  • Arrays: Arrays are first converted to primitive types, i.eprimitive valueThe original type is then converted according to the above conversion rules.
  • Objects: Same as arrays
Number(null)  // 0
Number(undefined)  //NaN
Number(true)  //1
Number(false)  //0
Number("11")  //11
Number("1.1 e+21"/ / 1.1 e+21 Number ("abc")  //NaN
Number([])   // 0
Number([0])  // 0
Number([1])  // 1
Number(["abc"])  NaN
Number({})  // NaN

Copy the code

4. Object conversion to another type (primitive type)

  • When an object is cast to another primitive type, the object is called firstvalueOf()Method, ifvalueOf()Method returns a primitive type, then the primitive type is returned
  • ifvalueOf()Method returns a primitive type orThe valueOf () methodIf the object does not exist, the call continuestoString()Method, iftoString()Method returns a primitive type, or throws an exception if it is not a primitive type.

Note: The rules for casting primitives are different for different types of objects, such as Date objects that call toString first

    var o1 = {
        valueOf() {return 1
        }
    }
    var o2 = {
        toString() {return 2
        }
    }
    var o3 = {
        valueOf() {return{}},toString() {return 3
        }
    }
    
    Number(o1)  //1
    Number(o2)  //2
    Number(o3)  //3
    

Copy the code

The valueOf method of O1 returns primitive type 1, so the result is 1

O2 has no valueOf method and calls toString to get primitive type 2, so the result is 2

O3 Has both valueOf and toString methods. If valueOf is called first, the original type is not returned. Therefore, toString is called again, and the original type 3 is returned

Let’s do another example

Call valueOf() to get [], not the original type. Call toString() to get an empty string. According to the Number conversion rules, the empty string is converted to a Number of 0, so Number([]) is 0

Implicit conversion of loose equality (==)

We know that loose equality has implicit conversions, so you can get true as long as the values on both sides are equal, you don’t have to be of the same type, so let’s see what kind of comparisons we have

Comparison between primitive types

1. The string type is compared with the number type

  • When a string type is compared to a number type,String typeWill be converted toNumeric types
  • When the string is a string consisting of pure numbers, it is converted to the corresponding number. When the string is empty, it is converted to0And the rest are converted toNaN. Small examples can be as follows:

    "1"/ / = = 1true
    ""= = 0 / /true
    "1.1 e+21"= = 1.1 e+21 / /true
    "Infinity" == Infinity  //true
    NaN == NaN  //falseBecause NaN is not equal to any value, including itselfCopy the code

2. Boolean types are compared to other types

  • As long asBoolean typeParticipate in the comparison, theBoolean typeIt will be converted firstNumeric types
  • Boolean typetrueto1.falseTo a ` ` 0

Small examples can be as follows:

true/ / = = 1true
false= = 0 / /true
true/ / = = 2false
""= =false // true
"1"= =true // true
Copy the code

By rule, booleans participate in the comparison, converting booleans to numeric types. In the first demo, true is converted to numeric type 1, the comparison becomes 1 == 1, and the result is true. In the second demo, false is converted to numeric type 0, the comparison becomes 0 == 0, and the result is true. In the third demo, true is converted to numeric type 1, and the comparison becomes 1 == 2, resulting in false. In the fourth demo, false is converted to numeric type 0, and the comparison becomes “” == 0. The string is first converted to a number based on the string compared to a number. The empty string is converted to numeric type 0, and the comparison becomes 0 == 0, so the result is true. The fifth demo is similar to the fourth, in that true is converted to numeric type 1, and the comparison becomes “1” == 1. According to the comparison between the string and the number, the string “1” is converted to numeric type 1, which becomes 1 == 1, so the result is true.

nullThe type andundefinedTypes are compared to other types

The first thing you need to know is null and undefined

Null: represents “null value”, represents an empty object pointer, uses typeof operation to get “object”, so it can be considered a special object value.

Undefined: declares a variable but does not assign a value to it. The default value of this variable is undefined.

Null and undefined are used separately:

nullScenario:
  • As the end of the prototype chain
  • As arguments to a function, indicating that the function’s arguments are not objects
undefinedScenario:
  • A variable is declared but no value is assigned to it. The default value of this variable isundefined
  • The function is not explicitly writtenreturn, returns by defaultundefined
  • When the function is called, no arguments are passed. The default parameter value isundefined
  • An attribute of the object is not assigned; the default value isundefined

Javascript specifies that null is loosely equal to undefined (==) and is equal to itself, but not loosely equal to all other values.

null == null   //true
undefined == undefined  //true
null == undefined  //true
null == 0  //false
null == false  //false
undefined == 0  //false
undefined == false  //false
null == []  //false
null == {}  //false
unfefined == []  //false
undefined == {}  //false
Copy the code

Object compared to the original type

When an object is compared with its original type, the object is converted to the original type according to the object conversion rules and then compared.

Here’s a quick example:

{} = = 0 / /false{} = ='[object object]'  // true[] = =false  // true= = [1, 2, 3]'1, 2, 3' // true
 
Copy the code

{},[],[1,2,3] : {},[],[1,2,3]

In the first example, the original value of {} is “[object object]”, and the comparison becomes “[object object]” == 0. [object object] is converted to NaN, and the comparison becomes NaN == 0.

In the second example, from the first analysis, the original value of {} is “[object object]”, the comparison becomes “[object object]” ==”[object object]”, so the result is true.

In the third example, the original value of [] is an empty string “”, and the comparison becomes “” == 0 “. Then, according to the rules for comparing string and number types, the string is converted to a number type, and the comparison becomes 0 == 0.

In the fourth example, according to the rules for converting an array to a primitive type, the result of the primitive type of the array is a string of elements separated by commas, so the comparison becomes “1,2,3” == “1,2,3”, so the result is true.

Objects are compared to objects

Let’s start with the storage of primitive and reference types.

Basic type: refers to the simple data segment stored in stack memory, the size of the data is determined, the size of the memory space can be allocated, they are stored directly by value, so they can be accessed directly by value.

Reference type: refers to the object stored in the heap memory, the variable name is stored in the stack memory, and the corresponding value is stored in the stack memory, this variable is actually stored in the stack memory: the address of the value in the heap memory, which is a pointer to the address in the heap memory.

Then the rule for comparing objects comes out:

The equality operator returns true if two objects refer to the same object, false otherwise.

var a = {};
var b = {};
a == b  // false

var c = [];
var d = [];
c == d  // false
Copy the code

Although both A and B hold an Object, these are two independent objects with different addresses. Same thing with c and D. So [] == [] is false, {} == {} is also false. How about the following?

var a = {};
var b = a;
a == b;
Copy the code

The variable b holds a pointer to a, pointing to the same object, so a == b.

So let’s look at the following example

[] = =! [] / /true{} = =! {} / /false
Copy the code

Javascript states that logic is not (!) Has precedence over the equality operator (==).

And what is the meaning of non?

Boolean() first converts its operation value to a Boolean value, then inverts it.

First example, let’s see! Boolean([]) (null, undefined, false, 0, “”, NaN, Boolean()) (null, undefined, false, 0, “”, NaN, Boolean()) Boolean([]) returns true, returns false, returns [] == false, returns [] == false, returns [] == false, returns [] == false, returns [] == false According to the string and number type comparison rule, the comparison is 0 == 0, which is true.

In the second example, the same as in the first example, first execute Boolean({}) to get true, then invert to get false, the comparison becomes {} == false, and now the comparison becomes the object type to be compared with the Boolean type. As we know from the previous example, {} toString() returns “[object object]”. ToString () returns “[object object]” The comparison becomes “[object object]” == 0, then according to the string and number type comparison rules,”[object object]” becomes the number type NaN, the comparison becomes NaN == 0,NaN is not equal to any value, obviously the result is false.

A ==1&&a==2&&a==3 Combine the object implicit conversion rules and give it a try!

How is the string concatenator (+) distinguished from the plus operator (+)

The following cases can be considered string concatenators

  • contains+The data on either side is a string
  • contains+Data on both sides, where one side is an object and the original value obtained is a string

Both cases are treated as String concatenators, which automatically convert data that is not a String to a String using String()

The following cases can be considered as plus operators

  • Both sides of the plus sign are numeric
  • Both sides of the plus sign are primitives, exceptString type, can be regarded asA plus sign. That means that both sides of the plus sign can be zeroBoolean.Number.null.undefinedIn this case, it must be the plus operator. Will notNumebrType of data executedNumber()Methods add up.
  • One side is a primitive type, except for strings, and the other side is an object, and the original value that the object gets is not a string.

It’s also worth mentioning that NaN adds to any number to be NaN,

So let’s look at the following example

"a" + "b"  // "ab"
"a"/ / + 1"a1"
"a"+ {} / /"a[object object]"
"a"+ [] / /"a"
"a" + true  // "atrue"
"a" + null  // "anull"
"a" + undefined // "aundefined"1 plus 2 over 3, 1 plustrue  // 2
 1 + null  // 1
 true + true/ / 2true + false/ / 1true + null   // 1
 false + null  // 0
 
 var c = {
     valueOf() {return 1;
     }
 }

 1 + undefined   // NaN
 true + undefined  // NaN
 true + c   // 2
 1 + c   // 2
 
 NaN + 1  // NaN
 NaN + null  // NaN
 
 [] + {}  // "[object object]"
 {} + []  // 0
Copy the code

It is worth mentioning here that Number(undefined) is NaN, and it is not hard to see why the above results are equal to NaN. So [] + {} and {} + [] are just one position, why is the result so different?

We know that the original value of [] is “”, and the original value of {} is [object object], which will not be repeated here. So in the first example, the concatenation equals “object object”, okay, so in the second example, why?

{}} is treated as a block of code, not a js object, so the operation can be written as +[]. The result is 0

You can operate their own see ~~~

Well, roughly is so much, but also read a lot of articles and written with the combination of elevation, lu again, really deepened the impression, give yourself a praise, hee Hee hee ~~~