How does JavaScript determine data type? 8 ways to share
How does JavaScript determine the data type? This article will share with you 8 ways to use JS to determine data type, which can effectively help work and interviews. The interviewer smiled slightly after reading it.
1. typeof
- can only recognize basic types and reference types
Note: null
, NaN
, document.all
Judgment
console.log(typeof null); // object console.log(typeof NaN); // number console.log(typeof document.all); // undefined
2, constructor
constuctor
Points to the constructor that created the instance object
Note that null
and undefined
do not have constructor
, and constructor
Can be rewritten
String.prototype.constructor = function fn() { return {}; }; console.log("云牧".constructor); // [Function: fn]
3, instanceof
- Syntax:
obj instanceof Type
- Function: Judgment
Whether obj
is an instance of theType
class, it can only be used to determine whether the reference data - is implemented: whether the prototype object of
Type
isobj
An object on the prototype chain - Note: The right operand must be a function or class
Handwritteninstanceof
:
function myInstanceof(Fn, obj) { // 获取该函数显示原型 const prototype = Fn.prototype; // 获取obj的隐式原型 let proto = obj.__proto__; // 遍历原型链 while (proto) { // 检测原型是否相等 if (proto === prototype) { return true; } // 如果不等于则继续往深处查找 proto = proto.__proto__; } return false; }
4. Is isPrototypeof
- on the prototype chain of the instance object?
- is basically equivalent to
instanceof
console.log(Object.isPrototypeOf({})); // false console.log(Object.prototype.isPrototypeOf({})); // true 期望左操作数是一个原型,{} 原型链能找到 Object.prototype
5. Object.prototype.toString
- Use the feature of function dynamic this
function typeOf(data) { return Object.prototype.toString.call(data).slice(8, -1); } // 测试 console.log(typeOf(1)); // Number console.log(typeOf("1")); // String console.log(typeOf(true)); // Boolean console.log(typeOf(null)); // Null console.log(typeOf(undefined)); // Undefined console.log(typeOf(Symbol(1))); // Symbol console.log(typeOf({})); // Object console.log(typeOf([])); // Array console.log(typeOf(function () {})); // Function console.log(typeOf(new Date())); // Date console.log(typeOf(new RegExp())); // RegExp
6. Duck type detection
- Check the type of its own attributes or the type of the execution result
- Usually used as a candidate solution
- Example:
kindof
andp-is-promise
p-is-promise:
const isObject = value => value !== null && (typeof value === "object" || typeof value === "function"); export default function isPromise(value) { return ( value instanceof Promise || (isObject(value) && typeof value.then === "function" && typeof value.catch === "function") ); }
kindof:
function kindof(obj) { var type; if (obj === undefined) return "undefined"; if (obj === null) return "null"; switch ((type = typeof obj)) { case "object": switch (Object.prototype.toString.call(obj)) { case "[object RegExp]": return "regexp"; case "[object Date]": return "date"; case "[object Array]": return "array"; } default: return type; } }
7、Symbol.toStringTag
- Principle:
Object.prototype.toString
will read the value - Applicable scenarios: custom type required
- Notes: Compatibility
class MyArray { get [Symbol.toStringTag]() { return "MyArray"; } } const arr = new MyArray(); console.log(Object.prototype.toString.call(arr)); // [object MyArray]
8. Waiting comparison
- Principle: Compare with a fixed value
- Applicable scenarios:
undefined
,window
,document
,null
, etc.
underscore.js:
Basic data type | Reference type | Notes | |
---|---|---|---|
√ | × | NaN、object、document.all | |
√ Part | √ | can be rewritten | |
× | √ | Multi-window, right constructor or class | |
× | √ | Be careful with null and undefined | |
√ | √ | Be careful with built-in prototypes | |
- | √ | Compatible as a last resort | |
× | √ | Identify custom objects | |
√ | √ | Special objects |
NaN and Number.NaN features
- typeof
is followed by a number
I am not equal to myself - delete
cannot be deleted
isNaN
- NaN
- , it will return
true
, otherwise it will returnfalse
console.log(isNaN(NaN)); // true console.log(isNaN({})); // true
Copy after loginNumber.isNaN
- NaN
console.log(Number.isNaN(NaN)); // true console.log(Number.isNaN({})); // false
Copy after loginOther judgments Whether
's methods <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>function isNaNVal(val) {
return Object.is(val, NaN);
}
function isNaNVal(val) {
return val !== val;
}
function isNaNVal(val) {
return typeof val === "number" && isNaN(val);
}
// 综合垫片
if (!("isNaN" in Number)) {
Number.isNaN = function (val) {
return typeof val === "number" && isNaN(val);
};
}</pre><div class="contentsignin">Copy after login</div></div>
- indexOf
- are not searchable
NaN
,includes
then you can[Recommended learning: javascript advanced tutorialconst arr = [NaN]; console.log(arr.indexOf(NaN)); // -1 console.log(arr.includes(NaN)); // true
Copy after loginThe above is the detailed content of How does JavaScript determine data type? 8 ways to share. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

The Go framework is a set of components that extend Go's built-in libraries, providing pre-built functionality (such as web development and database operations). Popular Go frameworks include Gin (web development), GORM (database operations), and RESTful (API management). Middleware is an interceptor pattern in the HTTP request processing chain and is used to add functionality such as authentication or request logging without modifying the handler. Session management maintains session status by storing user data. You can use gorilla/sessions to manage sessions.
