typeof do JavaScript
- Página Anterior Método Map JS
- Próxima Página Conversão de Tipos JS
typeof do JavaScript
Existem 5 tipos de dados diferentes que podem conter valores em JavaScript:
string
number
boolean
object
function
Existem 6 tipos de objetos:
Object
Date
Array
String
Number
Boolean
e 2 tipos de dados que não podem conter valores:
null
undefined
o operador typeof
Você pode usar typeof
O operador para determinar o tipo de dados de uma variável JavaScript.
Exemplo
typeof "Bill" // retorna "string" typeof 3.14 // retorna "number" typeof NaN // retorna "number" typeof false // retorna "boolean" typeof [1,2,3,4] // retorna "object" typeof {name:'Bill', age:19} // retorna "object" typeof new Date() // retorna "object" typeof function () {} // retorna "function" typeof myCar // retorna "undefined" * typeof null // retorna "object"
Atenção:
- O tipo de dados de NaN é número
- O tipo de dados do array é objeto
- O tipo de dados da data é objeto
- O tipo de dados de null é object
- O tipo de dados de uma variável não definida é undefined *
- O tipo de dados de uma variável não inicializada também é undefined *
Você não pode usar typeof
para determinar se um objeto JavaScript é um array (ou data).
Data original
O valor de dados originais se refere a um valor de dados simples sem atributos e métodos adicionais.
typeof
Os operadores podem retornar um dos seguintes tipos de dados originais:
string
number
boolean
undefined
Exemplo
typeof "Bill" // Returns "string" typeof 3.14 // Returns "number" typeof true // Returns "boolean" typeof false // Returns "boolean" typeof x // Returns "undefined" (if x has no value)
Complex data
typeof
The operator can return one of two complex types:
function
object
typeof
The operator will return "object" for objects, arrays, and null.
typeof
The operator will not return "object" for functions.
Exemplo
typeof {name:'Bill', age:19} // Returns "object" typeof [1,2,3,4] // Returns "object" (not "array", please note the example below) typeof null // Returns "object" typeof function myFunc(){} // Returns "function"
typeof
The operator will return for arrays "object"
, because in JavaScript, arrays are objects.
The data type of typeof
typeof
The operator is not a variable. It is just an operator. The operator (+ - * /) has no data type.
However,typeof
The operator is alwaysReturns a string(including the type of the operand).
The constructor attribute
constructor
The attribute returns the constructor of all JavaScript variables.
Exemplo
"Bill".constructor // Returns function String() {[native code]} (3.14).constructor // Returns function Number() {[native code]} false.constructor // Returns function Boolean() {[native code]} [1,2,3,4].constructor // retorna function Array()[native code] {name:'Bill',age:19}.constructor // retorna function Object()[native code] new Date().constructor // retorna function Date()[native code] function () {}.constructor // retorna function Function()[native code]
Você pode verificar a propriedade constructor para determinar se o objeto é um array (inclusive "Array"
a palavra):
Exemplo
function isArray(myArray) { return myArray.constructor.toString().indexOf("Array") > -1; }
ou, de forma mais simples, você pode verificar se o objeto éfunção de array:
Exemplo
function isArray(myArray) { return myArray.constructor === Array; }
Você pode verificar a propriedade constructor para determinar se o objeto é uma data (inclusive "Date"
a palavra):
Exemplo
function isDate(myDate) { return myDate.constructor.toString().indexOf("Date") > -1; }
ou, de forma mais simples, você pode verificar se o objeto éfunção de data:
Exemplo
function isDate(myDate) { return myDate.constructor === Date; }
Undefined
No JavaScript, a variável sem valor tem undefined
. O tipo também é undefined
。
Exemplo
let car; // O valor é undefined, o tipo também é undefined.
ao definir seu valor para undefined
pode esvaziar qualquer variável. O tipo também será undefined
。
Exemplo
car = undefined; // O valor é undefined, o tipo também é undefined.
O valor vazio
O valor vazio com undefined
Irrelevante.
Uma string vazia tem tanto valor válido quanto tipo.
Exemplo
let car = ""; // O valor é "", o tipo é "string"
Null
No JavaScript null
é chamado de 'nulo'. Deve ser algo que não existe.
Infelizmente, no JavaScript,null
O tipo de dados é um objeto.
Você pode considerar isso um bug no JavaScript.typeof null
É um objeto. O tipo deve ser null
。
Você pode definir o objeto como null
Para limpar o objeto:
Exemplo
let person = {firstName:"Bill", lastName:"Gates", age:19, eyeColor:"blue"}; person = null; // Agora o valor é null, mas o tipo ainda é objeto
Você também pode definir o objeto como undefined
Para limpar o objeto:
Exemplo
let person = {firstName:"Bill", lastName:"Gates", age:19, eyeColor:"blue"}; person = undefined; // Agora o valor e o tipo são undefined
Diferenças entre undefined e null
undefined
e null
Valores iguais mas tipos diferentes:
typeof undefined // undefined typeof null // object null === undefined // false null == undefined // true
- Página Anterior Método Map JS
- Próxima Página Conversão de Tipos JS