我需要一点语法帮助,使用三元运算符可以帮助我将正确的标记图标放在我的地图上。我有三个区域0、1和2,分别有唯一的图标0、1和2。
以前只有两个区域,所以这个三元运算符运行良好;
var icon = (area == 1) ? icon1 : icon0;
现在我需要为area2添加一个额外的第三个图标(icon2)。
我尝试了各种方法,但似乎就是无法做到正确。
我需要一点语法帮助,使用三元运算符可以帮助我将正确的标记图标放在我的地图上。我有三个区域0、1和2,分别有唯一的图标0、1和2。
以前只有两个区域,所以这个三元运算符运行良好;
var icon = (area == 1) ? icon1 : icon0;
现在我需要为area2添加一个额外的第三个图标(icon2)。
我尝试了各种方法,但似乎就是无法做到正确。
语法如下:
var icon = (area == 1) ? icon1 : (area == 2) ? icon2 : icon0;
但这开始变得复杂了。你可能最好只需创建一个函数来完成此工作:
var icon = getIcon(area);
function getIcon(area) {
if (area == 1) {
return icon1;
} else if (area == 2) {
return icon2;
}
return icon0;
}
对于那些对多种三元语法感到困惑的人(就像我一样),它是这样的:
var yourVar = condition1 ? someValue
: condition2 ? anotherValue
: defaultValue;
您可以添加任意数量的条件。
您可以在https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Conditional_Operator上进一步阅读。
怎样呢:
var icon = [ icon0, icon1, icon2 ][area];
area
变量包含一个数字。 - Pointyarea=2
,那么 C
就是该数组中的值吗?我甚至没想过可以同时定义和设置数组索引。 - JM-AGMSicon: { 1: icon1, 2: icon2 }[area] || icon0
。 - aaaaaa那么用一个对象字面量怎么样呢。
icons = {
0: icon0,
1: icon1,
2: icon2
}
icon = icons[area];
非常简单的方法
如果你的对象像这样:
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"
test1 ? test1 : (test2 ? test2 : 'some default value')
和 (test1 ? test1 : test2) ? test2 : 'some default value'
都会得到相同的结果。 - chharveyvar test = true; var result = test===true ? 'it is true' : test===false ? 'it is false' : 'it is null'
。这样当你将最后两个运算符分组时,test===true ? 'it is true' : (test===false ? 'it is false' : 'it is null')
,你会得到 'it is true'
(正确),但当你将前两个运算符分组时,(test===true ? 'it is true' : test===false) ? 'it is false' : 'it is null'
,你会得到 'it is false'
(不正确)。这个测试更好,因为它展示了隐式运算符分组。 - chharveyvar icon = (area == 0) ? icon0 : (area == 1) ? icon1 : icon2;
let age = prompt('age?', 18);
let message = (age < 3) ? 'Hi, baby!' :
(age < 18) ? 'Hello!' :
(age < 100) ? 'Greetings!' :
'What an unusual age!';
alert( message );
icon0
,则仍然可以采用这种方法。 - Justin Ethier