• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

directory

  1. Eight data types
  2. typeof Cannot distinguish [] {} null
  3. instanceof It can only be used to determine whether an object is dependent
  4. constructor Will be rewritten The judgment type is inaccurate
  5. Object.prototype.toString.call/applyThe most accurate `
  6. Type determination of ECMA encapsulationisArray

One eight data types

JS is weakly typed or dynamically typed, which means you don’t need to declare the type of a variable in advance; the type is automatically determined as the program runs. This means that you can use the same variable to hold different types of data

var a = 1; // Number
a = '1';  // String
a = [1];  // Array
a = {a:1};  // Object
Copy the code

1) Eight data types

  1. Value types (Stack memory)
  2. Reference type (Stack memory (pointer)-> heap memory)

The latest ECMAScript standard defines eight data types:

  • (Value type) primitive type in 7:

    • Number
    • String
    • Boolean
    • Null
    • Undefined
    • BigInt
    • Symbol
  • (Reference type) Object

2) Symbol

Symbol is a basic data type added to ES6. This can be created by calling the built-in Symbol() function, which dynamically generates an anonymous, globally unique value.

var a = Symbol(a);var b = Symbol(a); a === b// false

var c = Symbol('c'); // Symbol(c)

Copy the code

The Symbol stack cannot use the new command because Symbol is a primitive data type, not an object. You can take a string as an argument to provide a description of the newly created Symbol that can be displayed on the console or used as a string for easy differentiation.

var c = new Symbol('c');
Copy the code

3) The difference between basic data and quoted data

3.1) Basic data types
  • Access by value, manipulating the actual value stored in a variable
  • The value is saved inStack memoryOccupies a fixed amount of space
3.2) Reference data types
  • Values of reference types are accessed by reference
  • Stored in theObjects in heap memoryCannot directly access the memory space of the operation object

twotypeof Cannot distinguish [] {} null

The typeof command can determine all basic data types in JS (Null, Undefined, Boolean, String, Number), although Null uses typeof to return object strings, but does not matter

It is basic, but in complex scenarios such as object and NULL, array and object, function and object, etc., typeof can be difficult to use.

typeof 1; // 'number'
typeof '1'; // 'string'
typeof null; // 'object'
typeof undefined; // 'undefined'
typeof true; // 'boolean'
typeof Symbol('11') // 'symbol'
typeof 1n; // 'bigint'
typeof {} // 'object'
typeof [1]; // 'object'
typeof new Function(a)// 'function'
Copy the code

Note:

typeof {} // 'object' 
typeof [] // 'object' 
typeof(() = > {}) // 'function'
Copy the code
typeof 'a'                 // 'string'
typeof new String('a')     // 'object'
Copy the code
typeof undefined   // 'undefined'
typeof null  // 'object'
typeof Symbol(a)// 'symbol'
Copy the code

Three instanceofIt can only be used to determine whether an object is dependent

  • Can only be used to judge(The relationship between two objects belonging to the prototype chain).It is not necessarily possible to get the specific type of the object
  • Instanceof It is not appropriate to judge values of primitive types.It can only be used to determine whether an object is dependent
[1] instanceof Array; // true
[1] instanceof Object; // true

function a(){}
var b = new a();

b instanceof a; //true
b instanceof Object; //true
Copy the code

1) Note: null object {} judgment problem

let obj1 = {}
obj1 instanceof Object // true

let obj2 = Object.create(null)
obj2 instanceof Object; // false

let obj222 = Object.create(Object)
obj222 instanceof Object; // true

let obj3 = Object.create({})
obj3 instanceof Object; // true
Copy the code

fourconstructor Will be rewritten The judgment type is inaccurate

Each instance object can access its constructor via constructor, which is also based on the principle of prototype chain.

(new Function).constructor === Function; // true
(1).__proto__.constructor === Number; // true
(1).constructor === Number; // true
'1'.constructor === String; // true
'1'.__proto__.constructor === String; // true
[1].__proto__.constructor === Array; // true

var abc = new RegExp(a); abc.constructor ===RegExp; // true
Copy the code

Due to theUndefined and NULL are invalid objects.Therefore, there is no constructor attribute, the two values cannot be determined in this way.


undefined.__proto__.constructor // Cannot read property '__proto__' of undefined

null.__proto__.constructor // Cannot read property '__proto__' of undefined

Copy the code

Note: Constructor is overwritten, so judging the type is inaccurate

[1].__proto__.constructor = String;
[1].__proto__.constructor === Array; // false
Copy the code

fiveObject.prototype.toString.call/applyThe most accurate `

  • Object.prototype.toStringmethodsReturns the type string of the object.The most accurate.
  • For instance objects may be custom toString method, will cover the Object prototype. ToString, therefore, when using, had better add call
Object.prototype.toString.apply('5') // '[object String]'
Object.prototype.toString.call('5') // '[object String]'
Object.prototype.toString.call(5) // '[object Number]'
Object.prototype.toString.call([5]) // '[object Array]'
Object.prototype.toString.call(true) // '[object Boolean]'
Object.prototype.toString.call(undefined) // '[object Undefined]'
Object.prototype.toString.call(null) // '[object Null]'
Object.prototype.toString.call(new Function()); // '[object Function]'
Object.prototype.toString.call(new Date()); // '[object Date]'
Object.prototype.toString.call(new RegExp()); // '[object RegExp]'
Object.prototype.toString.call(new Error()); // '[object Error]'

Object.prototype.toString.call(null).slice(8, -1) // "Null" Object.prototype.toString.call(3).slice(8, -1) // "Number"
Copy the code

sixisArrayJudge null undefined

Array.isArray([]); // true
Copy the code
var isNull = function (obj) {
    return obj === null;
};
isNull(null); // true
Copy the code
var isUndefined = function (obj) {
	return obj === void 0; // void null // void undefined
}
isUndefined(undefined); // true
Copy the code

1) Turn to string

String(null)                 // 'null'
String(undefined)            // 'undefined'
String(true)                 // 'true'
String(1)                    / / '1'
String(-1)                   // '-1'
String(0)                    / / '0'
String(-0)                   / / '0'
String(Math.pow(1000.10))    // '1e+30'
String(Infinity)             // 'Infinity'
String(-Infinity)            // '-Infinity'
String({})                   // '[object Object]'
String([1[2.3]])            / / '1, 2, 3'
Copy the code

reference

  • Type judgment

conclusion

  • Symbol is created by calling the built-in Symbol() function, which dynamically generates an anonymous, globally unique value

  • Symbol is used to prevent the keys of objects from being overwritten

  • Typeof cannot distinguish [] {} null

  • Instanceof is not suitable for determining values of primitive types. It can only be used to determine whether an object is dependent

  • Constructor is overwritten, so judging the type is inaccurate

  • Instanceof is suitable for custom objects and can also be used to detect native objects. Instanceof fails when detecting between different iframes and Windows. Note the object.create (NULL) Object

  • Constructor can judge almost any type except null and undefined, but constructor is easily modified and cannot be used across iframes

  • Object. The prototype. ToString. Apply to all types, the most accurate