Javascript 多个三元运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7757549/
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
Multiple Ternary Operators
提问by Sam
I need a bit of syntax help with a ternary operator which will help me to put the correct marker icons on to my good map. I have three areas 0, 1 and 2 which have unique icons 0, 1 and 2.
我需要一些关于三元运算符的语法帮助,这将帮助我将正确的标记图标放在我的好地图上。我有三个区域 0、1 和 2,它们具有独特的图标 0、1 和 2。
I used to have just two areas so this ternary operator worked fine;
我曾经只有两个区域,所以这个三元运算符工作正常;
var icon = (area == 1) ? icon1 : icon0;
Now I need to add an additional third icon (icon2) for area2.
现在我需要为 area2 添加一个额外的第三个图标 (icon2)。
I've tried various methods but just can't seem to get it right.
我尝试了各种方法,但似乎无法正确解决。
回答by Justin Ethier
The syntax would be:
语法是:
var icon = (area == 1) ? icon1 : (area == 2) ? icon2 : icon0;
But this is starting to get complicated. You may well be better off just creating a function to do this work instead:
但这开始变得复杂。您最好只创建一个函数来完成这项工作:
var icon = getIcon(area);
function getIcon(area) {
if (area == 1) {
return icon1;
} else if (area == 2) {
return icon2;
}
return icon0;
}
回答by Pointy
How about:
怎么样:
var icon = [ icon0, icon1, icon2 ][area];
回答by Bruno
How about an object literal.
对象字面量怎么样。
icons = {
0: icon0,
1: icon1,
2: icon2
}
icon = icons[area];
回答by Sushil Dhayal
Very simple way
很简单的方法
If your object is like this:
如果你的对象是这样的:
var obj = {
x: true,
y: {
xy: 'some value'
}
}
var result = obj ? obj.y ? obj.y.xy ? obj.y.xy : 'N/A' : 'N/A' : 'N/A'
console.log(result) // "some value"
回答by Adam
For anyone that's confused about the multiple ternary syntax (like I was), it goes like this:
对于任何对多三元语法感到困惑的人(就像我一样),它是这样的:
var yourVar = condition1 ? someValue
: condition2 ? anotherValue
: defaultValue;
You can add as many conditions as you like.
您可以添加任意数量的条件。
You can read up further on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
您可以在https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator上进一步阅读
回答by John Hartsock
var icon = (area == 0) ? icon0 : (area == 1) ? icon1 : icon2;