使用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"
答案 0 :(得分:2)
这里有很多问题:
then
的多行格式,那么当您使用a = if b then c else d
之类的单行时,您只能使用if
。请勿使用then
s。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
。