In web front-end development, we often need to determine the data type of the variable. Since ECMAScript is loosely typed, there is a need for a means to detect the data type of a given variable--typeof is the operator responsible for providing this handy information.using the typeof operator on a value may return one of the following strings:
"Undefined"--if this value is undefined
"Boolean"--if this value is a Boolean value
"String"--if this value is a string
"Number"--if the value is numeric
"Object"--if this is an object or null
"Function"--if this value is a function
The return values of the commonly used typeof operators include number, String, Boolean, Undefined, object, and function. Such as:
Copy CodeThe code 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 demonstrate that the operands of the typeof operator can be either a variable (message) or a numeric literal. Note that TypeOf is an operator, not a function, so the parentheses in the example are not necessary (although they can be used).
From the above example, we find that the numbers created with number () are also returned with the value "Object" by TypeOf, because the constructor returns objects, so if we want to differentiate between numeric objects (number), String objects (strings), What about array objects (arrays), function objects, date objects (date), Boolean objects (Boolean), and JavaScript built-in objects such as Error objects? Here you can call the object's ToString method, such as:
Copy CodeThe code 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]"
// ...
Examples of typeof operator usages in JavaScript