var dots = svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("r", 5)
.attr("cx", xDots)
.attr("cy", yDots)
.style("fill", function(d) {
cd = d;
//
if(m.options.hicColors != null ) {
if(d.hic <= m.options.cutoffs[0]) {
d.fillColor = m.options.hicColors[0];
return m.options.hicColors[0];
} else if (d.hic > m.options.cutoffs[0] && d.hic <= m.options.cutoffs[1]) {
d.fillColor = m.options.hicColors[1];
return m.options.hicColors[1];
} else if(d.hic > m.options.cutoffs[1] && d.hic <= m.options.cutoffs[2]){
d.fillColor = m.options.hicColors[2];
return m.options.hicColors[2];
} else if(d.hic > m.options.cutoffs[2] && d.hic <= m.options.cutoffs[3]) {
d.fillColor = m.options.hicColors[3];
return m.options.hicColors[3];
} else {
d.fillColor = m.options.hicColors[4];
return m.options.hicColors[4];
}
}
})
我正在处理的程序包括采用一组形状并根据两个数组对它们进行着色,一个包含要使用的颜色,另一个包含截止值以决定使用哪种颜色。以前,这些总是5种颜色和4种截止,但现在我需要接受任何长度的数组。我不确定如何才能做到这一点。有没有人对我如何完成这项任务有任何建议?
请注意,颜色数组的长度始终比截止数组多一个。
答案 0 :(得分:1)
循环m.options.cutoffs
数组并执行类似于传递循环的实际索引的函数:
function analyse(hic, index){
if(hic > m.options.cutoffs[index] && hic <= m.options.cutoffs[index+1]){
return hic;
}
}
答案 1 :(得分:1)
既然你知道你将始终检查d.hic
是否在一个范围内,然后使用该范围的上限,检查可变长度数组的一种简单方法是从末尾开始向后工作直到找到值所在的范围。
var len = m.options.cutoffs.length;
for (var i = len - 1; i > 0; i--) {
if (d.hic > m.options.cutoffs[i - 1]) {
d.fillColor = m.options.hicColors[i];
return m.options.hicColors[i];
}
}
// if we got here, then d.hic falls within lowest range
d.fillColor = m.options.hicColors[0];
return m.options.hicColors[0];
这样,您甚至不必检查上限,因为如果d.hic
小于当前迭代的上限,则循环的上一次迭代将失败。
请注意,这可以很容易地从数组的开头到结尾。我个人只是使用向后的方法。
var len = m.options.cutoffs.length;
for (var i = 0; i < len; i++) {
if (d.hic <= m.options.cutoffs[i]) {
d.fillColor = m.options.hicColors[i];
return m.options.hicColors[i];
}
}
// still need to catch the case where d.hic is higher than the highest range
d.fillColor = m.options.hicColors[len - 1];
return m.options.hicColors[len - 1];
答案 2 :(得分:1)
您可以使用for循环和一个if语句
来完成此操作if(m.options.hicColors != null ) {
for (I = 0; I < m.options.hicColors.length; I ++) {
if(d.hic <= m.options.cutoffs[i]) {
d.fillColor = m.options.hicColors[i];
return m.options.hicColors[i];
}
}
}
d.fillColor = m.options.hicColors[m.options.hicColor.length - 1];
return m.options.hicColors[m.options.hicColor.length - 1];
这应该按原样在旧代码中运行。希望它有所帮助。