Using the typeof operator for a value may return one of the following strings:
"undefined" - if this value is not defined
"boolean" - if this value is a boolean
"string" - if this value is a string
"number" - if this value is a numerical value
"object" - if this is an object or null
"function" - if this value is a function
The return values of commonly used typeof operators include number, string, boolean, undefined, object and function. like:
The code copy is as follows:
var n;
console.log(typeof n); // "undefined"
n = 1;
console.log(typeof n); // "number"
n = "1";
console.log(typeof n); // "string"
n = false;
console.log(typeof n); // "boolean"
n = { name: "obj" };
console.log(typeof n); // "object"
n = new Number(5);
console.log(typeof n); // "object"
n = function() { return; };
console.log(typeof n); // "function"
These examples show that the operand of the typeof operator can be a variable (message) or a numeric literal. Note that typeof is an operator rather than a function, so parentheses in the example are not required (although they can be used).
From the example above, we found that numbers created with Number() will also be judged as objects by typeof and return the value "object". This is because the constructor returns all objects, so if we want to distinguish between numbers (Number) What should I do when JavaScript built-in objects such as String, Array, Function object, Date object, Boolean object, and Error object? Here you can call the toString method of the object, such as:
The code copy is as follows:
var n, res;
n = new Number(66);
res = Object.prototype.toString.call(n);
console.log(res); // "[object Number]"
n = new String("string");
res = Object.prototype.toString.call(n);
console.log(res); // "[object String]"
n = [];
res = Object.prototype.toString.call(n);
console.log(res); // "[object Array]"
// ...