简体   繁体   English

检查值的更好方法

[英]Better way to Check for values

Is there a more elegant way to do this? 有没有更优雅的方法可以做到这一点?

if(response && response.body && response.body.data) {
  const users = response.body.data
  dispatch(UserActions.usersReceived(users))
}

Meaning the response && response.body && response.body.data ? 意味着response && response.body && response.body.data

Php has something called isset(), but Js does not seem to have that function. Php有一个叫做isset()的东西,但是Js似乎没有那个功能。 Here is one of my favorites that I found on stack overflow a while back. 这是我一段时间前在堆栈溢出中发现的我的最爱之一。

user = {
  loc: {
        lat: 50,
        long: 9
  } 
}

user2 = null; 

has = function(obj, key) {
return key.split(".").every(function(x) {
    if(typeof obj != "object" || obj === null || !( x in obj)) {
        return false;          
    }
    obj = obj[x];
    return true;
});
}

console.log(has(user, 'loc.lat')); //true 
console.log(has(user, 'loc')); //true
console.log(has(user, 'loc.lat.ll')); // false
console.log(has(user2, 'd')); //false

If you won't check an object existence before calling its property, you can get exception and the execution stop. 如果在调用对象的属性之前不检查对象是否存在,则可以获取异常并停止执行。 Therefore, someone would suggest a try catch. 因此,有人建议尝试一下。

However, from my experience, it is better to check this way, explicit, easy to read and maintenance code is always good. 但是,以我的经验来看,最好以这种方式进行检查,显式,易于阅读且维护代码始终是好的。

No. But if it is a REST API (which looks like it is) I would recommend using a library for validations. 否。但是,如果它是REST API (看起来像这样),我建议使用库进行验证。 And joi is the best when you have to perform nested validations. 当您必须执行嵌套验证时, joi是最好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM