current position:Home>Front end - data type of JS Foundation

Front end - data type of JS Foundation

2022-01-26 22:15:01 Dunhuang Bi painting

data type

Data types are literal , Represents the types of various data . Data types exist in any language , Because the data are all kinds of .

JavaScript It mainly includes 8 Type of data ,8 Data types can be classified into basic type and reference type :

  • Basic data type

    1. number Numbers ( Contains integers and floating-point numbers )
    2. string character string
    3. boolean Boolean value
    4. undefined Undefined
    5. null Null pointer
    6. symbol Symbol
    7. bigint Large integer
  • Reference data type

    1. object object

You can usually use typeof Operator to see the data type , But notice , In detection null Value does not return null type , It is object type , This is a special case .

Number

JavaScript Indiscriminating integer 、 Floating point numbers, etc , Unity is called Number.typeof 100 obtain "number".

  • Numerical literals

    10、1.5、-20

  • Floating point precision problem

    console.log(0.1+0.2);

    console.log(0.7*100);

    JavaScript Used in IEEE 754 standard (opens new window) Of 64 Bit double precision floating point number . The operation of the value will first convert the value to binary , Under this standard, the decimal may be incomplete , So the final result is wrong .( Students who have the foundation of compilation can further understand )

    If in order to get relatively accurate results , Generally, the decimal will be converted to an integer before running , Finally divided by multiple . for example :console.log( (0.1*100+0.2*100)/100 );

  • Range of values

    According to the standard ,64 The length of the exponential part of a floating-point number is 11 Binary bits , It means that the maximum value of the exponential part is 2047(2 Of 11 The power minus 1). in other words ,64 The maximum value of the exponential part of a floating-point number is 2047, Half is negative , be JavaScript The range of values that can be expressed is 2 Of 1023 Second party to 2 Of 1024 Power ( Open range ), The number out of this range cannot represent .

    If a number is greater than or equal to 2 Of 1024 Power , Then it will happen “ A positive overflow ”, namely JavaScript It's impossible to express such a large number , And then it will return to Infinity. contrary , The maximum negative number is -Infinity.

    Infinity and -Infinity It's also a kind of number .

  • Special values

    NaN It's a special value , Its type is number, Represents a corrupted value , Usually occurs in When there is data that cannot be converted into numbers to participate in the operation produce .

String

Used to put a paragraph of text .typeof " Text text " obtain "string".

  • Literal of a string

    " written words " //  Double quotes 
    'ababa' //  Single quotation marks 
    `abcd` //  The quotation marks 
    

    All three kinds of quotation marks can be used to represent string data .

  • Escape character

    If you want to use quotation marks in a string :

    console.log(  "It's an apple."  ); // There is no problem using the other two kinds of quotation marks in one kind of quotation marks 
    
    console.log( "John:\"I love you.\"" ); // Use quotation marks with the same literal amount inside , You need to use  \  Escape symbol 
    

    Other escape meanings :

    img

  • String splicing

    Conduct + Operation time , If the data on either side is a string , Is the function of splicing

    console.log("123" + "4"); //"1234"
    console.log("123" + 4); //"1234"
    console.log("zzt" + "666"); //"zzt666"
    

Boolean

Boolean type has only two values : really true and false false. Used to judge .

typeof true obtain "boolean".

Undefined

The value of undefined type is undefined.

When the variable is not assigned , The default value is undefined.

typeof undefined obtain "undefined".

Null

null and undefined The meaning is very close to , All means “ No, ”.null You can think of it as one “ empty ” object , But it doesn't take up memory space . Usually, a variable is about to be given an object value in subsequent logic , But when you can't determine which object value it is at the beginning of definition , Give it an initial value null.

Be careful :typeof null obtain "object".

Symbol

symbol It is a data type with few application scenarios , This type of data is under development , I can't use . So just know

Symbol Value cannot be calculated

Symbol It's actually ES6 A primitive data type introduced , Use it to create a unique value . stay JS in , The basic data type is usually as long as “ It looks the same ” When judging equality , Namely true, And on certain occasions , We may need some unique values to ensure the normal operation of the program , For example, when creating attributes for objects , The existing attribute will not be overwritten . At this point, we need Symbol.

let s1 = Symbol() //  adopt Symbol Function to create a symbol data 

let s2 = Symbol() //  Create another 

console.log(s1) //  Output results :Symbol()
console.log(s2) //  Output results :Symbol()

//  They look the same , But not equal 
s1 == s2 // false

Conclusion : Every time you call Symbol() Will be in the program , Create a unique value

BigInt

The data type is in ES2020 The version just added , therefore 2020 The previous browser environment is not supported .

JavaScript It's always been bad in numbers , Because there is no bigint Before the type , Numbers can only represent -(2^53-1) to 2^53-1 Value of range , namely Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER, An integer calculation or representation outside this range will lose precision .

var num = Number.MAX_SAFE_INTEGER;  // -> 9007199254740991

num = num + 1; // -> 9007199254740992

//  Add... Again  +1  Can't operate normally after 
num = num + 1; // -> 9007199254740992

//  Two different values , But back to true
9007199254740992 === 9007199254740993  // -> true

therefore BigInt emerge as the times require , It is the 7 A primitive type , It can safely calculate large integer .

effect : Very large integer form ID And high-precision timestamp

In most cases, it can be used like a regular number type for example +, -, /, *, % wait . Yes bigint All the operations of , So is the result returned bigint

however 5n / 2n = 2n The result will cut off the decimal Keep the whole number % Empathy

establish BigInt Type values are also very simple , Just add... After the number n that will do . for example ,123 Turn into 123n. You can also use the global method BigInt(value) conversion , Enter the reference value For numbers or numeric strings .

const aNumber = 111;
const aBigInt = BigInt(aNumber);
aBigInt === 111n // true
typeof aBigInt === 'bigint' // true
typeof 111 // "number"
typeof 111n // "bigint"

Just add... At the end of the number n, Then we can calculate large numbers correctly :

1234567890123456789n * 123n;
// -> 151851850485185185047n

But there's a problem , In most operations , Can't be BigInt And Number A mixture of . Compare Number and BigInt Yes. (=== When comparing strictly It's not equal ), But you can't add them .

1n < 2 
// true

1n == 1 
//true

1n === 1 
//false

1n + 2
// Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions

 Unary operators  + I won't support it 
+'1'  It will translate into number Handle 
+1n Will report a mistake    The prompt cannot be converted to number

BigInt Support for :

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-JuvKwI1n-1639493463588)(https://user-gold-cdn.xitu.io/2020/1/18/16fb8c682a33ffd1?imageView2/0/w/1280/h/960/format/webp/ignore-error/1)]

Object type

JavaScript in object Types contain a lot of data , Array 、 Common object 、DOM node 、 Built-in objects 、 Functions and so on belong to obejct type .

  • Array

    An array can hold a set of data .

    • Value using [ Number sequence number ] Subscript , The serial number from 0 Start counting . When the value exceeds the maximum value of serial number , obtain undefined.

      let arr = [10,50,true,"Fly"];
      
      console.log(arr[2]); //true
      console.log(arr[6]); //undefined
      
    • The array can be stored in the array .

      let arr = [
          10,
          [
              " Summer Gardenia ",
              " Lucky charm ",
              [
                  true,
                  false
              ]
          ]
      ];
      
      console.log(arr[0]); //10
      console.log(arr[1][0]); //" Summer Gardenia "
      console.log(arr[2][1]); //false
      
    • Array has length attribute , You can get the number of data stored in the array .

      let a = [10,20];
      let b = [7,8,9];
      let c = [4,5,,6,];
      
      console.log(a.length); //2
      console.log(b.length); //3
      console.log(c.length); //4  the last one , If there is no value later , Not counting , In the middle of the , Even if there is no data between them, it is a number 
      
    • The array can take values , You can modify the value or add new value

      let arr = [4,5];
      arr[0] = 44;
      arr[2] = 6;
      console.log(arr); // [44,5,6]
      
      let arr2 = [7,8,9];
      arr2.length = 2;
      console.log(arr2); //[7,8]
      
  • Common object

    • Object to Key value pair In the form of data storage . The key is the attribute of the object , Value is a specific data .

      The naming rules of attributes and variables are somewhat similar , But attribute names are looser . Property names are allowed to be numbers , Nonstandard attribute names can be added " " Become a correct attribute name .

      let xz = {
              
          name : " Summer Gardenia ",
          "age" : 18,    // Attributes can be added  ""  Similar to the writing of string , Or you can skip it 
          "a b c" : true, // Irregular attribute names , Must be added  "", No mistake will be reported 
          20 : null // Natural numbers can act as attribute names , There is no need to add  ""
      };
      
    • Use... When taking values . The operator .

      let xz = {
              
          name : " Summer Gardenia ",
          age : 18,
          marry : false,
          friends : [" Lucky charm "," Si Si "]
      };
      
      console.log( xz.age ); //18
      console.log( xz.friends[0] ); //" Lucky charm "
      console.log( xz.hobby ); //undefined
      
    • When the attribute is a data , Use [] To take a value

      let xz = {
              
          name : " Summer Gardenia ",
          age : 18,
          marry : false,
          friends : [" Lucky charm "," Si Si "]
      };
      
      console.log( xz.name ); //" Summer Gardenia "
      console.log( xz["name"] ); //" Summer Gardenia "
      
      let a = "age";
      console.log( xz[a] ); //18
      console.log( xz.a ); //undefined
      
    • Object can take value , It can also be reassigned , You can also add attributes

      let obj = {
              a : 10};
      
      obj.a = 20;
      obj.b = 30;
      
      console.log(obj); // {a:20,b:30} 
      
  • Built-in objects

    JavaScript Objects that already exist in grammar , Call it a built-in object . These objects generally already contain many properties and methods , Sound and rich functions , We can use it directly . for example window document Math.

  • function

    JavaScript Functions in are also object types , Is a very special object .

    • Defined function

      let a = function(){
              
          // You can write anything here js Code 
      };
      
      function b(){
              
          // You can write anything here js Code 
      }
      
    • Function execution

      function fn(){
              
          alert(123);
      }
      // The function does not execute is , Internal functions do not run .
      
      // Function plus  ()  Can self execute 
      fn();
      
    • More knowledge about functions will be introduced in detail in the following chapters

object Data of type ,typeof You'll get object, But the function is typeof Get time function.

copyright notice
author[Dunhuang Bi painting],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262214551495.html

Random recommended