javascript 使用三元运算符设置变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11586466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:45:21  来源:igfitidea点击:

Using a ternary operator to set a variable

javascriptxml

提问by Greg Wiley

I am trying to use a ternary operator to check if the value of an XML element is null. If it is then I want the variable to be one thing. If not then I would like it to return the value of element. This is what I have so far.

我正在尝试使用三元运算符来检查 XML 元素的值是否为空。如果是,那么我希望变量是一回事。如果没有,那么我希望它返回元素的值。这就是我迄今为止所拥有的。

var rating = data.getElementsByTagName("overall_average")[0].childeNodes[0].length > 0 ? data.getElementsByTagName("overall_average")[0].childeNodes[0].nodeValue : "It is empty";

采纳答案by jo_asakura

The shortest way:

最短的方法:

var rating = (data.getElementsByTagName('overall_average')[0].childNodes[0] || {}).nodeValue || 'It is empty';

回答by ?ime Vidas

Here:

这里:

var node = data.getElementsByTagName( 'overall_average' )[0].childNodes[0];
var rating = node ? node.nodeValue : 'It is empty';

Note that this code throws (an error) in case there is not a single "overall_average" element in data, so you might want to guard against that case if necessary...

请注意,如果 中没有单个“overall_average”元素,则此代码将引发(错误)data,因此您可能希望在必要时防范这种情况...

回答by Daniel Li

Your ternary operation look fine to me. One thing I would suggest (for readability and brevity) is to define your overall_averageobject as a variable and reference it after.

你的三元操作对我来说很好。我建议的一件事(为了可读性和简洁性)是将您的overall_average对象定义为变量并在之后引用它。

var overall_average = data.getElementsByTagName("overall_average")[0].childeNodes[0];
var rating = overall_average.length > 0 ? overall_average.nodeValue : "It is empty";

Good luck!

祝你好运!