Before the beginning, fresh gram has an end

A long journey begins at a single step

1. 8 data types in JS

At present, there are 8 types of data types in JavaScript, mainly classified into two types: basic type and reference type

1.1. Differences between the two types

Primitive types are called simple types or value types, and reference types are called complex types.

Basic types (access by value) : When stored, the variable stores the value itself, so it is also called a value type;

Reference type (access by reference) : When stored, the variable stores only the address (reference), so it is called reference data type;

Introduce heap and stack:

Stack: Used to hold simple data fields

Heap: Used to hold a reference to a pointer from a simple data field in the stack

The difference between:

1. Stack (operating system) :

The operating system automatically allocates and releases the parameter value of the storage function, the value of local variables, etc. Its operation mode is similar to the stack in the data structure;

Simple data types are stored directly on the stack.

2. Heap (operating system) :

Store complex types, usually allocated by the programmer to release, if the programmer does not release, by the garbage collection mechanism to recover;

Complex data type references are stored on the stack, and the actual data is stored in the heap.

The reasons for this difference are as follows:

1. The basic type of data is simple and occupies a relatively small space. The memory is automatically allocated by the system.

2. Reference type data is complex and the complexity is dynamic. In order to reduce the loss caused by repeated creation and recycling of reference type data, the computer will first open up another part of space for it, namely heap memory, so as to facilitate the reuse of these data that occupy a large space;

Data in the heap is not destroyed immediately after a method ends. It is possible that the object will be referenced by other methods until the garbage collection mechanism of the system detects that the object is not referenced by any method.

To be specific, take a look at the actual impact:

// Basic data type
let  a = 1;
let  b = a;
b = 2;
console.log(a, b) / / 1. 2
Copy the code
// Reference the data type
let  obj1 = {a: 1.b: 2};
let  obj2 = obj1;
obj2.a = 20;
console.log(obj1.a, obj2.a) / / 20, 20
Copy the code

1.2 Specific segmentation of the two types:

For the sake of space, the first five basic types of platitudes have been skipped… , take a look at the following three:

1, the Symbol

Symbol is essentially a unique identifier that can be used as a unique attribute name for an object so that no one else can overwrite or overwrite the attribute value you set. Declaration method:

let id = Symbol("id");
Copy the code

The Symbol data type is characterized by uniqueness, even when values generated from the same variable are not equal.

let id1 = Symbol('id');
let id2 = Symbol('id');
console.log(id1 == id2);  //false
Copy the code

Another feature of the Symbol data type is that it is hidden; for·· in and object.keys() are not accessible

 let id = Symbol("id");
 let obj = {
  [id]:'symbol'
 };
 for(let option in obj){
     console.log(obj[option]); / / empty
 }
Copy the code

But also have to be able to access method: Object. GetOwnPropertySymbols, this method returns an array of all members is the current Object is used as the Symbol value of the property name.

let id = Symbol("id");
let obj = {
 [id]:'symbol'
};
let array = Object.getOwnPropertySymbols(obj);
console.log(array); //[Symbol(id)]
console.log(obj[array[0]]);  //'symbol'
Copy the code

Although this ensures the uniqueness of the Symbol, we do not rule out the possibility of using the same Symbol value more than once. To do this, the official provides a global registration and registration method: symbol.for ()

 let name1 = Symbol.for('name'); // Create a new one after detecting that it is not created
 let name2 = Symbol.for('name'); // Return when creation is detected
 console.log(name1 === name2); // true
Copy the code

Using this method, we can obtain the global symbol object through the parameter value. Conversely, we can obtain the parameter value through the symbol object. Yes, through symbol.keyfor ()

 let name1 = Symbol.for('name');
 let name2 = Symbol.for('name');
 console.log(Symbol.keyFor(name1));  // 'name'
 console.log(Symbol.keyFor(name2)); // 'name'
Copy the code

Finally, a reminder that the parameter is only used as an identifier when creating symbol type data, so symbol () is also acceptable.

2, BigInt,

2.1. What is it

The BigInt data type provides a way to represent integers greater than 2^53-1. BigInt can represent an arbitrarily large integer.

2.2. What problems have been solved

The Number type can only be an integer between -9007199254740991(-(2^53-1)) and 9007199254740991(2^53-1). Any value exceeding this range will lose precision. BigInt solves this problem

console.log(9007199254740999) / / 9007199254741000
console.log(9007199254740993= = =9007199254740992) //true
12
Copy the code

In the figure above, when values exceed the safe range supported by the Number data type, they are rounded, resulting in a loss of accuracy

2.3. How to use BigInt

1. Method 1: Append n to the end of the integer

console.log(9007199254740999n); / / 9007199254740999
Copy the code

Method 2: Call BigInt() constructor

let bigInt = BigInt("9007199254740999"); // Arguments passed to BigInt() are automatically converted to BigInt
console.log(bigInt); //9007199254740999n
Copy the code

2.4. Matters needing attention

1, BigInt does not use the unary plus operator

 console.log(+1n); // Uncaught TypeError: Cannot convert a BigInt value to a number
 console.log(-1n); //ok
Copy the code

BigInt and Number cannot be mixed

console.log(1n+5)
Copy the code

If you want to perform arithmetic calculations using BigInt and Number, you first need to determine in which type the operation should be performed. To do this, simply convert the operand by calling Number() or BigInt() :

BigInt(10) + 10n;    / / - 20 n
// or (operating in the same environment)
10 + Number(10n);    / / - 20
Copy the code

2.5. Summary:

The BigInt data type provides a way to represent integers greater than 2^53-1 or less than -2^53-1. BigInt can represent any large integer.

You cannot use a mixture of Number and BigInt operands to perform arithmetic operations. You need to explicitly convert one of the operands so that both operate in the same environment.

In addition, the unary plus (+) operator is not allowed on BigInt for compatibility reasons.

3. Everything is an Object.

Common reference types in Js include: Object, Array, Function, Date, RegExp, etc

3.1 Object Type

Special data types with attributes and methods;

There are two ways to create an Object instance. The first is to use the new operator followed by the Object constructor, for example;

let person = new Object(a); person.name ="Nicholas";
person.age = 29;
console.log(person instanceof Object); // true
Copy the code

Another approach is to use object literals. Such as:

let person = {
  name : "Nicholas", the age;29
}
console.log(person instanceof Object); // true
Copy the code

Note: When you define an Object through an Object literal, you don’t actually call the Object constructor.

3.2 Array type

Is to use a single variable name to store a series of values;

There are two basic ways to create arrays. The first is to use the Array constructor, for example:

let colors = new Array(a);console.log(colors instanceof Array);  // true
Copy the code

The second basic approach is to use array literals. Array literals are represented by a pair of square brackets containing array items separated by commas, for example:

let colors = ["red"."blue"."green"];
console.log(colors instanceof Array);  // true
Copy the code

3.3. Function type

Function types are also objects in JavaScript

A function is actually an object, and its name is actually a pointer to a function object, not bound to a function. Each Function is an instance of the Function type and has attributes and methods like any other reference type. Functions are usually defined using function declaration syntax :(function declaration promotion)

function sum (sum1,sum2) {
  return sum1 + sum2;
}
console.log(sum instanceof Function); // true
Copy the code

There is another way to define functions using function expressions:

let sum = function(sum1,sum2) {
  return sum1 +sum2 ;
};
console.log(sum instanceof Function); // true
Copy the code

3.4, other

Other types of reference specific details can see this article, more content is not a list:

Juejin. Cn/post / 691441…

2. Four judgment methods of data type

2.1, typeof

Let’s take a look at the usage:

// Basic type
console.log(typeof ""); 
console.log(typeof 1); 
console.log(typeof true); 
console.log(typeof undefined); 
console.log(typeof null); // object-- a little special, see below
console.log(typeof Symbol('id'))
console.log(typeof 9007199254740999n) 
console.log(typeof BigInt(9007199254740999)) 
​
// Reference type
console.log(typeof []); 
console.log(typeof function(){});
console.log(typeof {}); 
Copy the code

Results:

For base type null, use typeof to return a description of object.

summary

From the brainless console.log above, you can see that Typeof can be used to detect basic types (except null);

However, when the reference type is encountered, object is returned, so it cannot be accurately determined.

2.2, instanceof

Usage:

// Basic type
console.log('1' instanceof String) 
console.log(1 instanceof Number) 
console.log(true instanceof Boolean) 
​
// console.log(undefined instanceof undefined)
      // Uncaught TypeError: Right-hand side of 'instanceof' is not an object
// console.log(null instanceof null)
      // Uncaught TypeError: Right-hand side of 'instanceof' is not an objectconsole.log(typeof Symbol('id') instanceof Symbol) 
console.log(typeof 9007199254740999n instanceof BigInt) 
console.log(typeof BigInt(9007199254740999) instanceof BigInt) 
​
// Reference type
console.log([] instanceof Array) 
console.log(function () {} instanceof Function) 
console.log({} instanceof Object) 
Copy the code

Results:

summary

As you can see, instanceof can be used for reference type detection, but not for primitive types.

In addition, cannot be used to detect null and undefined, will throw errors.

2.3, the constructor

Let’s take a look at the usage:

// Basic type
console.log('1'.constructor === String)
console.log((1).constructor === Number)
console.log(true.constructor === Boolean)
// console.log(undefined.constructor === Boolean)
      // Uncaught TypeError: Cannot read properties of undefined (reading 'constructor')
// console.log(null.constructor === Boolean)
      // Uncaught TypeError: Cannot read properties of undefined (reading 'constructor')
console.log(Symbol('id').constructor === Boolean)
console.log(9007199254740999n.constructor === Boolean)
console.log(BigInt(9007199254740999).constructor === Boolean)
​
// Reference type
console.log([].constructor === Array)
console.log(function () {}.constructor === Function)
console.log({}.constructor === Object)
Copy the code

Results:

By skimming null, undefined, Symbol, and BigInt, constructor seems to be used to detect js base and reference types

But when it comes to archetypes and inheritance, there are problems, as follows:

function fun() {};
​
fun.prototype = new Array(a);let f = new fun();
​
console.log(f.constructor===fun); // false
console.log(f.constructor===Array); // true
Copy the code

Here, we define a function fun and point its prototype to an array, declare a type f for fun, and then test with constructor to find that it does not conform to expectations

summary

Skimming null, undefined, Symbol, and BigInt, constructor can be used to detect js primitives and reference types, but becomes invalidated when the object’s prototype changes.

2.4, the Object. The prototype. ToString. Call ()

Usage:

let test = Object.prototype.toString
​
// Basic type
console.log(test.call('str'))
console.log(test.call(1))
console.log(test.call(true))
console.log(test.call(null))
console.log(test.call(undefined))
​
console.log(test.call(Symbol('id')))
console.log(test.call(9007199254740999n))
console.log(test.call(BigInt(9007199254740999)))
​
// Reference type
console.log(test.call([]))
console.log(test.call(function () {}))
console.log(test.call({}))
Copy the code

Results:

Slice (8, -1).tolowerCase ().

It is possible to detect all types of data in javascript.

function fun() {};
​
fun.prototype = new Array(a);let f = new fun();
​
console.log(Object.prototype.toString.call(fun))
console.log(Object.prototype.toString.call(f))
Copy the code

Results:

summary

It can be seen that the Object. The prototype. ToString. Call () all of the data types can be used to detect js, perfect ~

2.5. Summary:

Is the text really uncomfortable to see? Here’s a chart:

Reference documentation links:

Developer.mozilla.org/zh-CN/docs/…

Es6.ruanyifeng.com/#docs/symbo…

Juejin. Cn/post / 684490…

Juejin. Cn/post / 691441…

Blog.csdn.net/yiyueqinghu…

Blog.csdn.net/m0_50914413…