当前位置:网站首页>Summary of JS data type judgment methods
Summary of JS data type judgment methods
2022-07-23 14:17:00 【Please code】
List of articles
- Write it at the front
- How to summarize
- typeof- Brief introduction
- typeof- Code example
- instanceof- Brief introduction
- instanceof Code example
- Realize one by yourself instanceof-while The way
- Realize one by yourself instanceof- recursively
- constructor- Brief introduction
- contructor- Code example
- Object.prototype.toString.call()- Brief introduction
- Object.prototype.toString.call()- Code example
- summary
Write it at the front
Write an article today about js Summary of data type verification methods ,js Data type verification has always been a very basic problem , But many people are confused , Basically, I will ask many questions during the interview , So today will be js To summarize the judgment methods of data types in , Which one is used in the specific project development process can be handled according to the actual situation ! I don't say much nonsense , Start water article , Bah , Start to summarize …
/* * @use: Implement different detection methods for detecting data types * @description: * + typeof * + instanceof * + construactor * + Object.prototype.toString.call([value]) * @SpecialInstructions: nothing * @Author: clearlove * @Date: 2022-07-04 17:26:57 * @LastEditTime: 2022-07-04 23:19:44 * @FilePath: /vue/Users/leimingwei/Desktop/LeiMingWei/ Source set /js relevant /js Data type judgment .js */
How to summarize
- typeof
- instanceof
- constructor
- Object.prototype.toString.call()
typeof- Brief introduction
typeof It can be used to detect basic data types
typeof It can also be used to detect reference data types , But it's not accurate
typeof When detecting basic data types null What was detected was object( Here's why )
typeof The detected data types are all lowercase strings
as a result of typeof The detection mechanism is to detect through computer binary
js When storing variables at the bottom , It will be in the lower part of the machine code of the variable 1-3 Bits store its type information :
000: object 010: Floating point numbers 100: character string 110: Boolean 1: Integers
null All machine codes are 0, therefore typeof It is also considered as an object when detecting
typeof- Code example
console.log(typeof NaN) //number
console.log(typeof null) //object
console.log(typeof undefined) //undefined
console.log(typeof 1) //number
console.log(typeof '') //string
console.log(typeof false) //boolean
console.log(typeof []) //object
console.log(typeof {
}) //object
console.log(typeof function () {
}) //function
console.log(typeof /^$/) //object
console.log(typeof Symbol()) //Symbol
instanceof- Brief introduction
Can be used to detect references ( complex ) Data type of
Basic data types cannot be detected
Because the prototype chain of data can be changed , So the detection is also inaccurate
The detection mechanism is to find out whether the prototype on the current instance object exists in the prototype object , So once the prototype chain is changed , What is detected is inaccurate
instanceof Code example
console.log(NaN instanceof Number) //false
console.log('' instanceof String) //false
console.log([] instanceof Array) //true
console.log({
} instanceof Object) //true
console.log(/^$/ instanceof RegExp) //true
console.log(function () {
} instanceof Function) //true
Malpractice realization - Change the direction of the instance prototype
let arr = []
console.log(arr.__proto__) //[]
arr.__proto__ = Object.prototype
console.log(arr.__proto__) // {}
console.log(arr instanceof Array) //false
Realize one by yourself instanceof-while The way
let customInstanceOf = (V, ANTETYPE) => {
let newPrototype = ANTETYPE.prototype
let protoV = Object.getPrototypeOf(V) //V.__proto__ Here for compatibility IE Browser
while (true) {
if (protoV === null) {
return false
}
if (protoV === newPrototype) {
return true
}
protoV = Object.getPrototypeOf(protoV)
}
}
console.log(customInstanceOf({
}, Array)) //false
Realize one by yourself instanceof- recursively
let dgInstanceOf = (V, P) => {
let res = false
let instanceP = P.prototype
let protoV = Object.getPrototypeOf(V)
if (protoV === null) {
res = false
} else {
instanceP === protoV ? res = true : dgInstanceOf(protoV, P)
}
return res
}
console.log(dgInstanceOf([], Array)) //true
constructor- Brief introduction
- Basic data types that can be detected
- You can detect references ( complex ) Data type of
- Because the constructor is used , Then the possibility of inaccurate detection is relatively large , Because the constructor of a function can be changed
contructor- Code example
let num = 1;
console.log(''.constructor === String) // true
console.log(NaN.constructor === Number) // true
console.log({
}.constructor === Object) // true
console.log([].constructor === Array) // true
console.log(/^$/.constructor === RegExp) // true
console.log(num.constructor === Number) //true
console.log(false.constructor === Boolean) // true
Malpractice realization - change contructor Value
let a = []
console.log(a.constructor === Array) //true
a.__proto__.constructor = {
}
console.log(a.constructor === Array) //false
Object.prototype.toString.call()- Brief introduction
- All data can be detected
- The disadvantage is that the writing method is more complex The detected results need to be processed
Object.prototype.toString.call()- Code example
console.log(Object.prototype.toString.call('')) //[object String]
console.log(Object.prototype.toString.call({
})) //[object Object]
console.log(Object.prototype.toString.call([])) //[object Array]
console.log(Object.prototype.toString.call(true)) //[object Boolean]
console.log(Object.prototype.toString.call(null)) //[object Null]
console.log(Object.prototype.toString.call(undefined)) //[object Undefined]
console.log(Object.prototype.toString.call(/^$/)) //[object RegExp]
console.log(Object.prototype.toString.call(function(){
})) //[object Function]
console.log(Object.prototype.toString.call(1)) //[object Number]
console.log(Object.prototype.toString.call(NaN)) //[object Number]
console.log(Object.prototype.toString.call(new Date())) //[object Date]
summary
The above are some methods we often use to judge the data type , In fact, in the daily development process, we use one more is typeof Methods , Although it cannot detect complex data types , But the basic data type is ok , Therefore, it is generally used and combined according to the actual situation , Instead of blindly using the last way that looks more comprehensive , Another article , Thank you !
边栏推荐
- [baiqihang] Niuer education helps colleges and universities visit enterprises, expand posts and promote employment
- Which is the difference between iqoo 10 pro and vivo X80 pro? Detailed parameter configuration comparison
- What level is the Core i7 1165g7 equivalent to? What grade does the i71165g7 belong to
- Is machine learning difficult to get started? Tell me how I started machine learning quickly!
- wacom固件更新错误123,数位板驱动更新不了
- 激励发生器、监测器
- How about the nuclear display performance of Ruilong R7 Pro 6850h? What level is it equivalent to
- Interface
- The difference between rtx3080ti and 3090. Which one is more cost-effective, rtx3080ti or 3090
- How many processors is Tianji 720 equivalent to Xiaolong? How about Tianji 720 equivalent to Xiaolong
猜你喜欢
随机推荐
Swift hex string to uicolor
What's the difference between core i9 12950hx and i9 12900hx
回文相关题目
视觉与智能学习近期期刊阅读与相关知识学习
Network security note 1 - Security of Internet Protocol
打家劫舍!
Canvas eraser function
Notes on the sixth day
接口interface
shell跑的時候需要的需要了解命令
Remember that a vulnhub target plane exercise successfully won the root permission
Is there a big gap between core i5 12490f and i5 12600K
Sampling and data driven
Interface
第六天笔记
激励发生器、监测器
Surrounded Regions
JS中不同的循环方式和注意事项总结
rtx3080ti和3090差距 rtx3080ti和3090哪个性价比高
鸡与蛋,产品与策略









