所以我创建了一个构建器,我正在尝试原型化。我想要一个方法来检查对象中的每个属性,看它是否为空,如果是,则返回密钥。如果属性是一个对象,我希望它也检查该子对象。
更新:
到目前为止我的代码:
function Properties(val1, val2, val3, val4){
this.prop1 = val1 || "";
this.prop2 = val2 || "";
this.prop3 = val3 || "";
this.prop4 = val4 || {};
}
Properties.prototype = {
isEmpty: function(){
for (key in this) {
if(typeof this[key] == "object" && this[key] !== null){
this[key].isEmpty();
} else {
if(!this[key]){
console.log(key);
}
}
}
}
}
var test = new Properties("Something", "", "", {subProp1: "Something Else", subProp2: "", subProp3: {subSubProp1: "", subSubProp2: "" }});
该方法应返回prop2,prop3,subProp2,subSubProp1,subSubProp2
答案 0 :(得分:1)
该方法不是对象的属性。您需要传入相关对象。您还可以传入一个数组来跟踪空键:
var emptyKeys = [];
function isEmpty(obj, keysArr) {
for (var key in obj) {
if (typeof obj[key] === "object" && obj.hasOwnProperty(key)) {
isEmpty(obj[key], keysArr);
} else {
if (obj[key] == "" || obj[key] == null) {
keysArr.push(key);
}
}
}
}
演示:http://jsfiddle.net/17rt0qy3/1/
如果你想在实际对象上使用它,只需在isEmpty
函数中添加上述函数:
isEmpty: function(){
var emptyKeys = [];
amIEmpty(this, emptyKeys);
return emptyKeys;
//Actual logic
function amIEmpty(obj, keysArr) {
for (var key in obj) {
if (key == "isEmpty") {
continue;
}
if (typeof obj[key] === "object" && obj.hasOwnProperty(key)) {
amIEmpty(obj[key], keysArr);
} else {
if (obj[key] == "" || obj[key] == null) {
keysArr.push(key);
}
}
}
}
}
演示:http://jsfiddle.net/17rt0qy3/2/
使用上面的演示对象的小提琴:http://jsfiddle.net/17rt0qy3/3/
Aaand另一个编辑,这只会它更清洁:log
键,但
isEmpty: function(obj, keys) {
keys = keys || [];
obj = obj || this;
for (var key in obj) {
if (typeof obj[key] === "object" && obj.hasOwnProperty(key)) {
this.isEmpty(obj[key], keys)
} else {
if (obj[key] == "" || obj[key] == null) {
keys.push(key);
}
}
}
return keys;
}