2016-11-22 35 views
0

我在對象中有兩個鍵。如果STATUSURL值是有一定的價值,我檢查了以下三種情形驗證對象內的空值

  • ,那麼成功
  • 如果STATUSURL值爲「」,errorUrl值不得「」
  • 如果STATUSURL和errorUrl都是空,然後失敗

我正在使用下面的工作代碼,但想知道是否有更好的方案來以更簡單的方式做到這一點。

var obj = { 
    statusUrl: "", 
    errorUrl: "" 
}; 
function validate(key) { 
    if (!obj.hasOwnProperty(key) || obj[key] === "") { 
     return 1; 
    } 
} 
var flag = validate("statusUrl"); 
if (flag) { 
    var result = validate("errorUrl") ? "failure" : "success"; 
} 
console.log(result) 

jsfiddle

回答

0

您可以簡化您這樣的代碼

var obj = { 
 
    statusUrl: "", 
 
    errorUrl: "" 
 
}; 
 

 
function validateObject(obj) { 
 
    return (obj.statusUrl != "" || (obj.statusUrl == "" && obj.errorUrl != "")); 
 
} 
 

 
var result = validateObject(obj) ? "success" : "failure"; 
 

 
console.log(result);

0

概括你的需求,無論是STATUSURL或errorUrl具有價值意味着成功,否則意味着失敗。如何

var obj = { 
    statusUrl: "", errorUrl: "" 
}; 
var result = (obj.statusUrl || obj.errorUrl) ? "success": "failure"; 
console.log(result) 

https://jsfiddle.net/j09Lynma/

+0

**如果STATUSURL值爲 「」,errorUrl值不能爲 「」 ** - 如果'statusUrl'爲空並且'errorUrl'不是那麼'成功' – Weedoze

+0

@Weedoze在您投票之前您是否嘗試過我的代碼? – Simon

0
var obj = { 
    statusUrl: "", 
    errorUrl: "" 
}; 

var result = "failure"; 

if (obj.statusUrl) { 
    result = 'success'; 
} else { 
    if (obj.errorUrl) { 
    result = 'success'; 
    } 
} 

console.log(result); 
+1

歡迎來到堆棧溢出!雖然這段代碼可能會解決這個問題,但包含一個解釋確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 – prasanth

0

這裏有一個 「簡單」 的方式

var obj = { 
    statusUrl: "", 
    errorUrl: "" 
    }, 
    result = validate(obj); 

console.log(result); 

function validate(obj){ 
    if (obj.statusUrl !== "") { 
    //1. if statusUrl value is having some value, then success 
    return "success" 
    } else if(obj.errorUrl !== "") { 
    //2. if statusUrl value is "", errorUrl value must not be "" 
    return "success" 
    } else { 
    //3. if both statusUrl and errorUrl are empty, then failure 
    return "failure" 
    } 
} 

truthy/falsey值檢查時小心。

var a = "0", 
    b = 0; 

console.log(!a); //false 
console.log(!b); //true 
0

試試這個:

var obj = { 
 
    statusUrl: "", 
 
    errorUrl: "" 
 
}; 
 

 
function validate(obj) { 
 
    if (obj.statusUrl != "" || (obj.statusUrl != "" && obj.errorUrl != "") || (obj.statusUrl == "" && obj.errorUrl != "")) { 
 
     return 1; 
 
    } 
 
} 
 

 
var output = validate(obj) ? "success" : "failure"; 
 

 
console.log(output);

0

使用本:

var result=(obj.statusUrl && obj.statusUrl!=""?"success":(obj.errorUrl && obj.errorUrl!=""?"success":"failure")) 

console.log(result)