当前位置:网站首页>Js判断数据类型的4种⽅式
Js判断数据类型的4种⽅式
2022-07-28 22:06:00 【仙女爱吃鱼】
1.Js判断数据类型的4种⽅式
Js数据类型 es5 6种数据类型:string、number、boolean、object(Data、function、Array)、null、undefined
Es6中新增了⼀种数据类型:symbol:表示独⼀⽆⼆的值,最⼤的⽤法是⽤来定义对象的唯⼀属性名,⽆论何时都不相等
var s1 = Symbol("symbol");
1.typeof
- 对于基本类型,除 null 以外,均可以返回正确的结果。
- 对于引⽤类型,除 function 以外,⼀律返回 object 类型。
- 对于 null ,返回 object 类型。
- 对于 function 返回 function 类型。
Typeof NaN = number
Typeof null = object
Typeof object = function Object/Array/String/Number/Boolean/Date/RegExp都是构造函数
Typeof {} = object
typeof console.log = ‘function’ 函数本身
typeof console.log() = ‘undefined’ 运⾏函数,默认返回undefined
2.instanceof
测试A是否是B的实例,⽐较A._proto是否和B.prototype相等
,instanceof 只能⽤来判断两个对象是否属于实例关系, ⽽不能判断⼀个对象实例具体属于哪种类型。
[] instanceof Array
{} instanceof Object
instanceof (A,B) = {
var L = A.__proto__;
var R = B.prototype;
if(L === R) {
// A的内部属性 __proto__ 指向 B 的原型对象
return true;
}
return false;
}
3.constructor
- null 和 undefined 是⽆效的对象,因此是不会有 constructor 存在的,这两种类型的数据需要通过其他⽅式来判断。
‘’.constructor === ‘String’
New Number(1).constructor === ‘Number’
New Function().constructor === ‘function’
4.toString
Object的原型⽅法,返回当前对象的[[Class]]
Object.prototype.toString.call(‘’) // [[Object String]]
Object.prototype.toString.call(new Error()) ; // [object Error]
Object.prototype.toString.call(document) ; // [object HTMLDocument]
Object.prototype.toString.call(window) ; //[object global] window 是全局对象 global 的引⽤
边栏推荐
- 2022 welder (Junior) work license questions and answers
- Plato Farm有望通过Elephant Swap,进一步向外拓展生态
- PowerCLi 批量添加esxi到vCenter
- My second uncle is angry and swipes the screen all over the network. How can he cure my spiritual internal friction?
- Best practices for migration of kingbasees v8.3 to v8.6 of Jincang database (3. Kingbasees migration capability support system)
- Worthington丨Worthington胰蛋白酶抑制剂说明书
- GhostNets on Heterogeneous Devices via Cheap Operations
- 从XSS Payload学习浏览器解码
- 失败率高达80%,数字化转型如何正确完成战略规划?
- [self] - question brushing - string
猜你喜欢
随机推荐
RHCE first day
Okaleido生态核心权益OKA,尽在聚变Mining模式
E-commerce data model design
剑指 Offer 64. 求1+2+…+n,逻辑运算符短路效应
Learn browser decoding from XSS payload
电商数据模型设计
[self] - question brushing - dynamic programming
【自】-刷题-动态规划
Multisensor fusion positioning (III) -- inertial technology
websocket心跳机制(保活机制)
Pycharm new project
Class, leetcode919 -- complete binary tree inserter
Compatibility description between kingbasees and Oracle (3. Common functions)
In depth analysis of integrated learning xgboost (Continued)
2022t elevator repair examination questions and simulation examination
EN 1873屋面用装配附件.塑料单个屋面灯—CE认证
[data mining engineer - written examination] Dahua shares in 2022
台式机dp接口在哪(主机没有dp接口怎么办)
How powerful can top "hackers" be? Internet access without signal, expert: high-end operation!
剑指 Offer 41. 数据流中的中位数








