空值判断 && 类型判断

一、判断一个对象是不是空------4种方法

	1.Object.getOwnPropertyNames()
	返回值是对象中属性名组成的数组;如果是空数组,即为空;
	eg:
	let obj={
		name:"123",
		age:12
	}
	console.log((Object.getOwnPropertyNames(obj)))  //["name", "age"]  不是空
	
	
	2.转化成字符串
	str==="{}"  进行判断,true,即为空;
	eg:
	let obj={};
	let str=JSON.stringify(obj);
	console.log(str==="{}")  //true  是空
	
	
	3.for in
	判断对象中有没有key键名,true,即为空;
	eg:
	let obj={};
	function kongobj(obj){
		for(let key in obj){
			return false;
		}
		return true
	}
	console.log(kongobj(obj))  //true  是空
	
	
	4.Object.keys()------判断有无键名 
	  Object.values()------判断有无键值
	  如果为空数组,对象即为空;
	eg:
	let obj={};
	console.log(Object.keys(obj))  //[ ]
	console.log(Object.values(obj))  //[ ]

二、判断某个变量类型的方式------有3种
1、typeof
2、instanceof
3、Object.prototype.toString.call()

	1、typeof
	
	console.log(typeof null)  //object
	console.log(typeof {});  //object
	console.log(typeof []);  //object
	console.log(typeof function(){});  //function
	console.log(typeof Symbol());  //symbol
	
	
	2、instanceof  (被判断的变量  instanceof  变量类型)
	
	console.log([] instanceof Array)  //true
	console.log({} instanceof Object)  //true
	console.log(function(){} instanceof Function)  //true
	
	
	3、Object.prototype.toString.call()---js判断数据类型最终解决方案
	
	console.log(Object.prototype.toString.call({}))  //[object Object]
	console.log(Object.prototype.toString.call([]))  //[object Array]
	console.log(Object.prototype.toString.call(function(){}))  //[object Function]
	console.log(Object.prototype.toString.call("nihao"))  //[object String]
	console.log(Object.prototype.toString.call(1))  //[object Number]
	console.log(Object.prototype.toString.call(Symbol))  //[object Function]
	console.log(Object.prototype.toString.call(null))  //[object Null]
	console.log(Object.prototype.toString.call(undefined))  //[object Undefined]
	console.log(Object.prototype.toString.call(new Date()))  //[object Date]
	console.log(Object.prototype.toString.call(Math))  //[object Math]
	console.log(Object.prototype.toString.call(new Set()))  //[object Set]
	console.log(Object.prototype.toString.call(new Map()))  //[object Map]
	console.log(Object.prototype.toString.call(new WeakMap()))  //[object WeakMap]

对象空值判断 和 变量类型判断 就这么多啦。

发布了3 篇原创文章 · 获赞 1 · 访问量 24

猜你喜欢

转载自blog.csdn.net/LHP_nbone/article/details/105526844
今日推荐