typeof de JavaScript

typeof de JavaScript

En JavaScript hay 5 tipos de datos diferentes que pueden contener valores:

  • string
  • number
  • boolean
  • object
  • function

Hay 6 tipos de objetos:

  • Object
  • Date
  • Array
  • String
  • Number
  • Boolean

y 2 tipos de datos que no pueden contener valores:

  • null
  • undefined

operador typeof

Puede usar typeof operadores para determinar el tipo de datos de una variable JavaScript.

Ejemplo

typeof "Bill"                 // devuelve "string"
typeof 3.14                   // devuelve "number"
typeof NaN                    // devuelve "number"
typeof false                  // devuelve "boolean"
typeof [1,2,3,4]              // devuelve "object"
typeof {name:'Bill', age:19}  // devuelve "object"
typeof new Date()             // devuelve "object"
typeof function () {}         // devuelve "function"
typeof myCar                  // devuelve "undefined" *
typeof null                   // devuelve "object"

Prueba personalmente

Atención:

  • El tipo de datos de NaN es número
  • El tipo de datos del array es objeto
  • El tipo de datos de la fecha es objeto
  • El tipo de datos de null es object
  • El tipo de datos de una variable no definida es undefined *
  • El tipo de datos de una variable sin inicializar también es undefined *

No puede usar typeof para determinar si un objeto JavaScript es un array (o fecha).

Fecha original

El valor de datos originales se refiere a un valor de datos simple sin propiedades y métodos adicionales.

typeof Los operadores pueden devolver uno de los siguientes tipos de datos originales:

  • string
  • number
  • boolean
  • undefined

Ejemplo

typeof "Bill"              // Devuelve "string"
typeof 3.14                // Devuelve "number"
typeof true                // Devuelve "boolean"
typeof false               // Devuelve "boolean"
typeof x                   // Devuelve "undefined" (si x no tiene valor)

Prueba personalmente

Datos complejos

typeof El operador puede devolver uno de los dos tipos de datos complejos:

  • function
  • object

typeof El operador typeof devuelve "object" para los objetos, arrays y null.

typeof El operador typeof no devuelve "object" para las funciones.

Ejemplo

typeof {name:'Bill', age:19} // Devuelve "object"
typeof [1,2,3,4]             // Devuelve "object" (no "array", atención al siguiente ejemplo)
typeof null                  // Devuelve "object"
typeof function myFunc(){}   // Devuelve "function"

Prueba personalmente

typeof El operador typeof devuelve "object" para los arrays. "object", ya que en JavaScript los arrays son objetos.

Tipos de datos de typeof

typeof El operador typeof no es una variable. Es solo un operador. Los operadores (+ - * /) no tienen ningún tipo de datos.

pero,typeof El operador siempreDevuelve una cadenaque incluye el tipo de operando).

Atributo constructor

constructor La propiedad devuelve el constructor de todas las variables JavaScript.

Ejemplo

"Bill".constructor                // Devuelve function String()  {[código nativo]}
(3.14).constructor                // Devuelve function Number()  {[código nativo]}
false.constructor                 // Devuelve function Boolean() {[código nativo]}
[1,2,3,4].constructor             // devuelve function Array()   {[native code]}
{name:'Bill',age:19}.constructor  // devuelve function Object()  {[native code]}
new Date().constructor            // devuelve function Date()    {[native code]}
function () {}.constructor        // devuelve function Function(){[native code]}

Prueba personalmente

Puede verificar la propiedad constructor para determinar si el objeto es un array (incluso "Array" una palabra):

Ejemplo

function isArray(myArray) {
  return myArray.constructor.toString().indexOf("Array") > -1;
}

Prueba personalmente

o más simple, puede verificar si el objeto esFunción de array:

Ejemplo

function isArray(myArray) {
  return myArray.constructor === Array;
}

Prueba personalmente

Puede verificar la propiedad constructor para determinar si el objeto es una fecha (incluso "Date" una palabra):

Ejemplo

function isDate(myDate) {
  return myDate.constructor.toString().indexOf("Date") > -1;
}

Prueba personalmente

o más simple, puede verificar si el objeto esFunción de fecha:

Ejemplo

function isDate(myDate) {
  return myDate.constructor === Date;
}

Prueba personalmente

No definido

En JavaScript, el valor de una variable sin valor es undefined. El tipo también es undefined

Ejemplo

let car;    // El valor es undefined, el tipo también es undefined.

Prueba personalmente

Al establecer su valor en undefinedpuede vaciar cualquier variable. El tipo también será undefined

Ejemplo

car = undefined;    // El valor es undefined, el tipo también es undefined.

Prueba personalmente

Un valor nulo

Un valor nulo con undefined Irrelevante.

Una cadena vacía tiene tanto un valor válido como un tipo.

Ejemplo

let car = "";    // El valor es "", el tipo es "string"

Prueba personalmente

Nulo

En JavaScript, null es "nulo". Debería ser algo inexistente.

Desafortunadamente, en JavaScript,null El tipo de datos es un objeto.

Puede considerar que es un bug en JavaScript.typeof null Es un objeto. El tipo debería ser null

Puede establecer el objeto en null Para vaciar el objeto:

Ejemplo

let person = {firstName:"Bill", lastName:"Gates", age:19, eyeColor:"blue"};
person = null;    // Ahora el valor es null, pero el tipo sigue siendo objeto

Prueba personalmente

También puede establecer el objeto en undefined Para vaciar el objeto:

Ejemplo

let person = {firstName:"Bill", lastName:"Gates", age:19, eyeColor:"blue"};
person = undefined;   // Ahora el valor y el tipo son undefined

Prueba personalmente

Diferencias entre undefined y null

undefined y null Valores iguales pero tipos diferentes:

typeof undefined           // undefined
typeof null                // objeto
null === undefined         // falso
null == undefined          // verdadero

Prueba personalmente