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
typeof
Puede juzgar los tipos de string
, number
, boolean
, undefined
, symbol
, function
etc., pero no el tipo null
de 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: typeof
No se puede distinguir null
, Object
, Array
. typeof juzga que los tres tipos devuelven 'objeto'.
2. Determinar si es una matriz
Método 1
Úselo instanceof
para determinar si los datos son una matriz.
[] instanceof Array // true
Cabe señalar que instanceof
no 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