我是靠谱客的博主 大气冬天,这篇文章主要介绍判断数据类型的方法?instanceof原理?判断空对象? typeof null?typeof NaN?,现在分享给大家,希望可以做个参考。

判断数据类型的方法

typeof

判断数据类型,它返回表示数据类型的字符串(返回结果只能包括number,boolean,string,function,object,undefined)

typeof判断变量是否存在(如if(typeof a!="undefined"){...})

复制代码
1
2
3
4
5
6
7
8
typeof null "object" typeof undefined "undefined" typeof NaN "number"

instanceof

A instanceof B 可以判断A是不是B的实例,返回一个布尔值,由构造类型判断出数据类型

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[1,2,3] instanceof Array true function Car(make, model, year) { this.make = make; this.model = model; this.year = year; } const auto = new Car('Honda', 'Accord', 1998); console.log(auto instanceof Car); // expected output: true console.log(auto instanceof Object); // expected output: true

Object下的toString.call()

复制代码
1
2
3
4
5
6
Object.prototype.toString.call([]) "[object Array]" Object.prototype.toString.call({}) "[object Object]" Object.prototype.toString.call(function(){}) "[object Function]"

 contructor

复制代码
1
2
3
4
5
[].constructor ƒ Array() { [native code] } "123".constructor ƒ String() { [native code] }

判断空对象

JSON.stringify()

复制代码
1
2
3
4
5
6
var obj = {} var obj1 = new Object() JSON.stringify(obj) "{}" JSON.stringify(obj1) "{}"

Object.keys

复制代码
1
2
3
let obj3 = {} Object.keys(obj3).length 0

Object.getOwnPropertyNames

复制代码
1
2
3
4
5
6
7
8
9
10
Object.getOwnPropertyNames(obj3) [] obj3 = {a:1, [Symbol('name')]: 'yr'} {a: 1, Symbol(name): "yr"} Object.getOwnPropertyNames(obj3) ["a"] //判断length为0则为空对象

for...in

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function isEmptyObject(obj){ for(var key in obj){ return false }; return true }; var a1={}; isEmptyObject(a1) true var b1 = {a:2} isEmptyObject(b1) false

 

 

最后

以上就是大气冬天最近收集整理的关于判断数据类型的方法?instanceof原理?判断空对象? typeof null?typeof NaN?的全部内容,更多相关判断数据类型的方法?instanceof原理?判断空对象?内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(69)

评论列表共有 0 条评论

立即
投稿
返回
顶部