JS判断对象或数组非空

1. if(obj)成立条件

let a = 0;//false
let b = 0.0;//false
let c = '';//false
let d = ' ';//true
let e = null;//false
let f = "null";//true
let g = undefined;//false
let h = "undefined";//true
let i = true;//true
let j = false;//false
let k = [];//true
let l = {};//true
let arr = [a, b, c, d, e, f, g, h, i, j, k, l];
for (let i = 0; i < arr.length; i++) {
	if (arr[i]){
		console.log(i + 1 + "--" + arr[i]);
	}
}

打印结果:
在这里插入图片描述

所以,if(obj)相当于:

if(obj != 0 && obj != 0.0 && obj != '' && obj != null && obj != undefined && obj != false){}

2. 判断不是空数组"[]"

方式一:
	Array.prototype.isPrototypeOf(obj) && obj.length > 0
方式二:
	obj && obj.length > 0
方式三:
	Array.prototype.isPrototypeOf(obj) && JSON.stringify(obj) !== '[]'

说明:

  • isPrototypeOf() 方法用于测试一个对象是否存在于另一个对象的原型链上。即判断 Object 是否存在于 obj 的原型链上。需要注意的是,js 中一切皆是对象,也就是说,Object 也存在于数组的原型链上,因此这里数组需要先于对象检验。
  • isPrototypeOfinstanceof operator 是不一样的。在表达式 object instanceof AFunction 中,检测的是 AFunction.prototype 是否在object 的原型链中,而不是检测 AFunction 自身。
  • 该方法属于 ES3 标准,现代浏览器均支持,包括 IE
  • 参考:https://www.cnblogs.com/xxhuan/p/6582114.html

3. 判断对象是否为空"{}"

参考:https://www.cnblogs.com/jpfss/p/9105119.html

4. 判断对象中是否包含指定key

方式一:
	let obj = {name: "james", age: 18};
	let keys = Object.keys(obj);
	console.log(keys.indexOf("name")> -1);//true
方式二:
	console.log(obj.hasOwnProperty("name"));//true

5. 遍历一个对象

方式一:
	let obj = {name: "curry", age: 18};
	for (let key in obj) {
		let value = obj[key];
		console.log(key + "--" + value);
	}
方式二:
	let keys = Object.keys(obj);//ES6
	for (let i = 0; i < keys.length; i++) {
		let key = keys[i];
		let value = obj[key];
		console.log(key + "--" + value);
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值