Método JS para juzgar el tipo de datos

Tipos de datos de JavaScript

  • cadena: cadena
  • número: número
  • booleano: valor booleano
  • indefinido indefinido
  • nulo: valor vacío
  • objeto: objeto (incluyendo matrices y funciones)
  • símbolo: símbolo, valor único (ES6 nuevo)

1. Defectos de tipo

typeofPuede juzgar los tipos de string, number, boolean, undefined, symbol, functionetc., pero no el tipo nullde 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

Nota: typeofNo se puede distinguir null, Object, Array. typeof juzga que los tres tipos devuelven 'objeto'.

2. Determinar si es una matriz

Método 1

Úselo instanceofpara determinar si los datos son una matriz.

[] instanceof Array // true

Cabe señalar que instanceofno se puede utilizar para juzgar si es un tipo de objeto, porque una matriz también es un objeto.

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

Método 2

El constructor también puede determinar si se trata de una matriz.

[].constructor === Array // true

Método 3

Object.prototype.toString.call()Se pueden obtener varios tipos de objetos.

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

Este método también se puede utilizar para determinar si se trata de un objeto de promesa.

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

Método 4

Utilice el método isArray() de la matriz para juzgar.

Array.isArray([]) // true

Método 5

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

3. Juzgar si es un objeto

Método 1 (recomendado)

Object.prototype.toString.call() Se pueden obtener varios tipos de objetos.

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

Método 2

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

Supongo que te gusta

Origin blog.csdn.net/m0_53808238/article/details/130640681
Recomendado
Clasificación