search
HomeWeb Front-endJS TutorialA brief discussion on data type detection in javascript_javascript skills

1. JavaScript data
Javascript data is divided into two types: simple data and complex data. Simple data includes five types: number, string, boolean, undefined and null; there is only one type of complex data, object. [Friendly thanks to Teacher Li Zhan here, > is so expressive and impressive]

2. JavaScript data type detection
1. The universal typeof
Let’s first test how to obtain simple data types through typeof. Don’t say anything, the code is king:
Copy the code The code is as follows:

/ / Get the data type of variable obj
function getType(obj) {
return typeof (obj);
}
/*Constant get type*/
alert(getType(1)); //number
alert(getType("jeff wong")); //string
alert(getType(true)); //boolean
alert(getType(undefined)); //undefined
alert(getType(null)); //object
/*Variable get type*/
var num = 1;
var str = "jeff wong";
var flag = true;
var hell = undefined;
var none = null;
alert(getType(num)); //number
alert(getType(str)); //string
alert(getType( flag)); //boolean
alert(getType(hell)); //undefined
alert(getType(none)); //object

As you can see In that way, through the typeof operator, the first four simple data types are completely expected, but typeof null returns object. It should be noted that null is the only value of the null type, but null is not an object, and a variable with a null value is not an object, so the null type cannot be correctly obtained directly through typeof. To correctly obtain simple data types, just add some improvements to getType:
Copy code The code is as follows:

function getType(obj) {
return (obj === null) ? "null" : typeof (obj);
}

Let’s try it next Complex data type object:
Copy code The code is as follows:

function Cat() {
}
Cat.prototype.CatchMouse = function () {
//do some thing
}
// Get the data type of variable obj
function getType(obj) {
return (obj === null) ? "null" : typeof (obj);
}
var obj = new Object();
alert(getType(obj)); //object
var func = new Function();
alert(getType(func)); //function
var str = new String("jeff wong");
alert(getType(str)); // object
var num = new Number(10);
alert(getType(num)); //object
var time = new Date();
alert(getType(time)); / /object
var arr = new Array();
alert(getType(arr)); //object
var reg = new RegExp();
alert(getType(reg)); / /object
var garfield = new Cat();
alert(getType(garfield)); //object

We see that except Function (please note the case) is returned Function, whether it is the common built-in objects of JavaScript such as Object, String or Date, etc., or a custom function, all returned by typeof are all objects without exception. But for custom functions, we prefer to get its "true face" (in the example, Cat, not object), and obviously, typeof does not have this conversion processing capability.
2. Constructor, I want to say I love you loudly
Since the universal typeof sometimes has no solution, how do we judge whether a variable is a custom function instance? We know that all objects in JavaScript have a constructor attribute. This attribute can help us determine the object data type, especially for custom functions:
Copy code The code is as follows:

var obj = "jeff wong";
alert(obj.constructor == String); //true
obj = new Cat();
alert(obj.constructor == Cat); //true

However, you can also test it with the following code:
Copy code The code is as follows:

//alert(1.constructor); //Numeric constant error Numeric constant has no constructor
var num = 1;
alert(num.constructor == Number); //true
alert("jeff wong".constructor == String); //true
var str = "jeff wong";
alert(str.constructor == String); //true
var obj= null;
alert(obj.constructor); //null has no constructor attribute
none = undefined;
alert(obj.constructor); //undefined has no constructor attribute

Experiments have shown that numeric constants, null and undefined do not have constructor attributes.
At this point, will you be as happy as Lou Zhu and think it’s finally done? The following code may also be of some inspiration and excavation:
Copy code The code is as follows:

function Animal() {
}
function Cat() {
}
Cat.prototype = new Animal();
Cat.prototype.CatchMouse = function () {
/ /do some thing
}
var obj = new Cat();
alert(obj.constructor == Cat); //false? ?
alert(obj.constructor == Animal); //true understanding

It turns out that constuctor is not so easy to use in the case of prototype chain inheritance. What to do?
3. Intuitive instanceof
Hey, please instanceof makes a grand appearance. Judging from its naming, it seems to be to obtain an instance of a certain object. I don’t know if this is the right way to understand it? Anyway, let’s improve the above code and test it first:
Copy the code The code is as follows:

function Animal() {
}
function Cat() {
}
Cat.prototype = new Animal();
Cat.prototype.CatchMouse = function () {
//do some thing
}
var garfield = new Cat();
alert(garfield instanceof Cat); //true no doubt
alert(garfield instanceof Animal); //true It’s understandable

Okay, regarding the data type detection of JavaScript, Louzhu has summarized it here. I hope someone with a heart can add more.
Statement
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools