简体   繁体   English

多个三元运算符

[英]Multiple Ternary Operators

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.我尝试了各种方法,但似乎无法正确解决。

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;
}

怎么样:

var icon = [ icon0, icon1, icon2 ][area];

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上进一步阅读

How about an object literal.对象字面量怎么样。

icons = {
    0: icon0,
    1: icon1,
    2: icon2
}

icon = icons[area];

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"

var icon = (area == 0) ? icon0 : (area == 1) ? icon1 : icon2;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM