将具有 2 个要求的 Javascript if 语句设置为一行
Setting a Javascript if statement with 2 requirements to one line
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]
存在的话,最好是陛下......否则,请执行代码中要执行的任何操作。
相关文章:
- 在函数内设置全局变量值&if语句
- 如何将窗口[VariableName]设置为if语句条件
- 在javascript if语句中取消设置$_POST
- Chrome 的开发工具或 Firebug 中是否存在“设置下一个语句”功能?
- 根据 if / else 语句修改设置“选项”值
- 下面如何设置 if isset 语句
- 使用 if 语句设置面向对象的 JavaScript 变量
- 如何在querybuilder中的var中设置BETWEEN语句
- 将具有 2 个要求的 Javascript if 语句设置为一行
- 我可以使用按钮来调用函数,但不能从搜索设置的if语句中调用,但可以调用任何其他函数
- 如何设置具有多个条件的if语句,该语句使用有效条件's变量
- 有没有一种更简洁的方法来设置一个条件语句,以便为变量的任意值集执行
- JavaScript:switch语句未设置隐藏元素值
- 为什么函数语句在使用设置为方法时不创建函数
- 如何使用switch语句设置变量的值,该语句的表达式是作为dom元素id设置的变量
- 当将两个变量设置为相同的dom元素时,Jquery语句的值不为true
- 如何设置多个Angular UI-router resolve语句
- 使用ko.computed和if语句来设置对象的可观察属性
- NodeJS抱怨对象是未定义的,如果它是在if语句中设置的
- 使用基于$_POST值的if-else语句设置javascript变量