Home > Web Front-end > JS Tutorial > Usage examples of typeof operator in JavaScript_Basic knowledge

Usage examples of typeof operator in JavaScript_Basic knowledge

WBOY
Release: 2016-05-16 16:53:21
Original
1007 people have browsed it

Using the typeof operator on a value may return one of the following strings:
"undefined" - if the value is undefined
"boolean" - if the value is a Boolean value
"string ” - if this value is a string
"number" - if this value is a numeric 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. For example:

Copy code The 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 illustrate that the operand of the typeof operator can be a variable (message) or a numerical 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 found that the number created with Number() will also be judged as an object by typeof and the value "object" will be returned. This is because the constructor returns all objects, so if we want to What to do when you want to distinguish JavaScript built-in objects such as Number, String, Array, Function, Date, Boolean and Error. Woolen cloth? Here you can call the toString method of the object, such as:

Copy the code The 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]"

// ...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template