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 也存在于数组的原型链上,因此这里数组需要先于对象检验。
- isPrototypeOf 和 instanceof operator 是不一样的。在表达式 object instanceof AFunction 中,检测的是 AFunction.prototype 是否在object 的原型链中,而不是检测 AFunction 自身。
- 该方法属于 ES3 标准,现代浏览器均支持,包括 IE。
- 参考:https://www.cnblogs.com/xxhuan/p/6582114.html
3. 判断对象是否为空"{}"
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);
}