完整代码如下
created() {
var obj1 = {
a: "1",
b: "2",
},
obj2 = {
a: "1",
},
obj3 = {};
console.log(
this.isEmptyObject1(obj1),
this.isEmptyObject1(obj2),
this.isEmptyObject1(obj3)
); // false false true
console.log(
this.isEmptyObject2(obj1),
this.isEmptyObject2(obj2),
this.isEmptyObject2(obj3)
); // false false true
console.log(
this.isEmptyObject3(obj1),
this.isEmptyObject3(obj2),
this.isEmptyObject3(obj3)
); // false false true
console.log(
this.isEmptyObject4(obj1),
this.isEmptyObject4(obj2),
this.isEmptyObject4(obj3)
); // false false true
},
methods: {
isEmptyObject1(data) {
return JSON.stringify(data) == "{}";
},
isEmptyObject2(data) {
for (var key in data) {
return false;
}
return true;
},
// Object.getOwnPropertyNames() 获取到对象中的属性名,存到一个数组中,返回数组对象
isEmptyObject3(data) {
var arr = Object.getOwnPropertyNames(data);
// console.log(arr); // ['a', 'b'] ['a'] []
return arr.length == 0;
},
// ES6 的 Object.keys() 与Object.getOwnPropertyNames() 效果一致
isEmptyObject4(data) {
var arr = Object.keys(data);
return arr.length == 0;
},
},
控制台输出