【发布时间】:2022-06-14 23:23:20
【问题描述】:
我正在使用 Cytoscape JS 制作网络查看器,为此我需要通过 JSON 对象提供样式。我基本上想要一个热图,所以我在 255 个类别中选择它们,每个类别都有自己的颜色。由于我不打算写 255 个条目,我想用循环来完成。然而,这种结合让我很头疼,我真的不知道我在哪里愚蠢。
var create_stylesheet = function(){
var to_return =[
{
'selector': 'node', 'style': {'content': 'data(label)', 'background-color': 'BlueViolet'}
},
{
'selector': 'edge', 'style': {'label': 'data(score)'}
}]; // <- this entry is for basic node labels and stuff. It needs to be first.
//For loop that assigns a colour to each category.
//As the red RGB value goes up, the blue RGB goes down. creating a gradient from cold to warm.
// In the program warmer colours have a higher score.
for(i = 0; i <= 255; i++){
var cat = `.cat_${i}`;
var colour = `rgb(${i}, 0, ${255-i})`;
var to_append =
{
'selector': cat, 'style': {'line-color': colour}
};
//Here I'd like to add to_append to the to_return variable.
}
return to_return; //Return the finished stylesheet.
}
谢谢,非常感谢您的帮助。
【问题讨论】:
-
你为什么要写 JSON?只需创建标准的 JS 对象,然后使用
JSON.stringify()最后获取 JSON。 -
您的
to_return变量是一个数组,所以为什么不直接将新的to_append值推送给它。to_return.push(to_append)
标签: javascript json iteration combine