Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将带有2个要求的Javascript if语句设置为一行_Javascript - Fatal编程技术网

将带有2个要求的Javascript if语句设置为一行

将带有2个要求的Javascript if语句设置为一行,javascript,Javascript,我有上面的代码,每个都需要一个if语句来检查是否有内容,我的输出是下面的代码 var status = result.locations[index].status; var operator = result.locations[index].operator; var original = result.locations[index].original; var produced = result.locations[index].produced; var href = result.l

我有上面的代码,每个都需要一个
if
语句来检查是否有内容,我的输出是下面的代码

var status = result.locations[index].status;
var operator = result.locations[index].operator;
var original = result.locations[index].original;
var produced = result.locations[index].produced;
var href = result.locations[index].more;

我需要从文章顶部的代码中逐行复制这一点。最好的简化方法是什么,以保持代码整洁,不产生5行if语句,而1行或2行就可以了。

不确定为什么要这样做,但是:

if (result.locations[index] && result.locations[index].status){
    var status = result.locations[index].status;
} else {
    var status = '';
}
var status = (result.locations[index] && result.locations[index].status ? result.locations[index].status : '');

但是,如果
result.locations[index]
存在,则最好先确定一下。。。否则,请在代码中执行任何操作。

您的问题是尝试使用“deep”javascript对象的路径访问该对象的属性

这是一个常见的问题:

在javascript中没有内置的方法来实现这一点

有很多库可以做到这一点,例如,使用,这将类似于(我还没有测试它,所以我不知道索引部分是否可以工作,但你知道了):

如果对象的结构始终是上面的结构(即,该属性仅处于一个深度级别),并且您不希望出现“falsy”,那么您可以自己编写“test”函数:

var status = selectn("locations." + index + ".status", result) || ''

几行有什么问题?JS中没有像Groovy中那样的“elvis”操作符,如果这是您正在搜索的…看不到向下投票的原因,这是一个恰当的问题…@webeno我想向下投票是因为我们不知道OP为什么要将其减少到一行。我怀疑他是在寻找一种不那么冗长的方式来观察对象内部的“深度”…@webeno haters会讨厌的,我喜欢更干净的代码,目前我有6行代码,比如
var status=result.locations[index].status
,需要改成if语句,比如OP,所以我想缩短代码。澄清一下:我从不失望voted@phtrivier我不明白,这是一个简单的问题,有一个简单的答案。。。我认为OP不需要给出这样的理由…你可能想
typeof
test
instance[propertyName]
如果你想要返回“”、0、False等值。是的,当然,我会澄清这一点!
var status = result.locations[index] && result.locations[index].status || ''; 
var status = selectn("locations." + index + ".status", result) || ''
function safeGet(instance, propertyName, defaultValue) {
    // As pointed by AlexK, this will not work 
    // if instance[propertyName] can be anything Falsy ("", 0, etc...)
    // If it's possible, get a library that will do 
    // the full series of insane checks for you ;)
    if (instance && instance[propertyName)) {
      return instance[propertyName];
    } else {
      return defaultValue;
    }
}

var location = result.locations[index]; // Potentially undefined, but safeGet will deal with it

var status = safeGet(location, "status", "");
var operator = safeGet(location, "operator", "DEFAULT_OPERATOR");
...