JS method of judging data type

JavaScript data types

  • string: string
  • number: number
  • boolean: Boolean value
  • undefined: undefined
  • null: empty value
  • object: object (including arrays and functions)
  • symbol: symbol, unique value (ES6 new)

1. Defects of typeof

typeofYou can judge the types of string, number, boolean, undefined, symbol, functionetc., but not the type nullof object.

var str = "Hello";
var num = 123;
var bool = true;
var undf;
var nl = null;
var obj = {
    
    name: "John", age: 25};
var arr = [1, 2, 3];
var func = function() {
    
    };
var sym = Symbol("mySymbol");

console.log(typeof str);    // 输出:string
console.log(typeof num);    // 输出:number
console.log(typeof bool);   // 输出:boolean
console.log(typeof undf);   // 输出:undefined
console.log(typeof nl);     // 输出:object
console.log(typeof obj);    // 输出:object
console.log(typeof arr);    // 输出:object
console.log(typeof func);   // 输出:function
console.log(typeof sym);    // 输出:symbol

Note: typeofCannot distinguish null, Object, Array. typeof judges that all three types return 'object'.

2. Determine whether it is an array

method 1

Use instanceofto determine whether the data is an array.

[] instanceof Array // true

It should be noted that instanceofit cannot be used to judge whether it is an object type, because an array is also an object.

[] instanceof Object // true
{
    
    } instanceof Object // true

Method 2

The constructor can also determine whether it is an array.

[].constructor === Array // true

Method 3

Object.prototype.toString.call()Various types of objects can be obtained.

Object.prototype.toString.call([]) === '[object Array]' // true
Object.prototype.toString.call({
    
    }) === '[object Object]' // true

This method can also be used to determine whether it is a promise object.

let obj = new Promise()
Object.prototype.toString.call(obj) === '[object Promise]' // true

Method 4

Use the array's isArray() method to judge.

Array.isArray([]) // true

Method 5

Object.getPrototypeOf(val) === Array.prototype // true 

3. Judging whether it is an object

Method 1 (recommended)

Object.prototype.toString.call() Various types of objects can be obtained.

Object.prototype.toString.call({
    
    }) === '[object Object]' // true

Method 2

Object.getPrototypeOf(val) === Object.prototype // true 

Guess you like

Origin blog.csdn.net/m0_53808238/article/details/130640681