我正在尝试使用Coffeescript设置条件,以便在图形图上为两个变量设置fillColor;lastVisibility和curr_visibility。我的语法不对劲。有什么建议
for set in datasets
line.push
data: set,
lines:
show: true
fill: true
opacity: 0.7
fillColor: if lastVisibilty == 0 & curr_visibility == 0
then "#C90E30"
else lastVisibilty == 0 & curr_visibility == 1
then "#439C32"
else lastVisibilty == 1 & curr_visibility == 0
then "#C90E30"
else
"#439C32"
这里有很多问题:
then
在使用a = if b then c else d
单线(例如)时使用,如果您使用的多行形式,if
则不使用then
。else
意思是有多个分支else if
。&
并且&&
是不同的东西,&
是按位运算符,&&
是您要寻找的逻辑合取。将这些调整应用于您的代码,您将得到:
for set in datasets
line.push
data: set,
lines:
show: true
fill: true
opacity: 0.7
fillColor: if lastVisibilty == 0 && curr_visibility == 0
"#C90E30"
else if lastVisibilty == 0 && curr_visibility == 1
"#439C32"
else if lastVisibilty == 1 && curr_visibility == 0
"#C90E30"
else
"#439C32"
但是,循环内的条件逻辑并不依赖set
(即循环不变),因此您应将其排除在外:
fillColor = if lastVisibilty == 0 && curr_visibility == 0
"#C90E30"
else if lastVisibilty == 0 && curr_visibility == 1
"#439C32"
else if lastVisibilty == 1 && curr_visibility == 0
"#C90E30"
else
"#439C32"
for set in datasets
line.push
data: set,
lines:
show: true
fill: true
opacity: 0.7
fillColor: fillColor
或者更好的方法是,将所有不变的内容推入循环之外,以进一步阐明代码:
fillColor = if lastVisibilty == 0 && curr_visibility == 0
"#C90E30"
else if lastVisibilty == 0 && curr_visibility == 1
"#439C32"
else if lastVisibilty == 1 && curr_visibility == 0
"#C90E30"
else
"#439C32"
lines =
show: true
fill: true
opacity: 0.7
fillColor: fillColor
for set in datasets
line.push
data: set,
lines: lines
或者,由于for循环是一个表达式,您可以这样说:
fillColor = if lastVisibilty == 0 && curr_visibility == 0
"#C90E30"
else if lastVisibilty == 0 && curr_visibility == 1
"#439C32"
else if lastVisibilty == 1 && curr_visibility == 0
"#C90E30"
else
"#439C32"
lines =
show: true
fill: true
opacity: 0.7
fillColor: fillColor
line = ({ data: set, lines: line } for set in datasets)
假设line
在循环之前那是空的;如果不是,那么您可以使用Array.prototype.concat
:
line = line.concat({data: set, lines: line } for set in datasets)
将循环的数据附加到line
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句