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

Setting a Javascript if statement with 2 requirements to one line

本文关键字:设置 语句 一行 if Javascript      更新时间:2023-09-26
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;

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

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

我需要从帖子顶部的代码中每行重现这一点。简化每个代码以保持代码整洁并且当 1 或 2 行时不产生 5 行 if 语句的最佳方法是什么。

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

不知道为什么要这样做,但是:

var status = (result.locations[index] && result.locations[index].status) ? result.locations[index].status : ""

您的问题是尝试使用其路径访问"深度"JavaScript对象的属性。

这是一个常见的问题:

Javascript:通过将路径作为字符串传递给对象来获取深层值

使用字符串键访问嵌套的 JavaScript 对象

在javascript中没有内置的方法可以做到这一点。

有很多库可以做到这一点,例如,使用 selectn,这将变成类似的东西(我没有测试过它,所以我不知道索引部分是否有效,但你明白了(:

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

如果你的对象结构总是上面的结构(也就是说,属性只是在一个深度级别(,并且你不期望"falsy",你可以简单地自己编写"test"函数:

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");
...
var status = result.locations[index] && result.locations[index].status || ''; 

不过,如果result.locations[index]存在的话,最好是陛下......否则,请执行代码中要执行的任何操作。