我正在使用 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.
}
謝謝,非常感謝您的幫助。
編輯:感謝和我一起思考的人。我做錯的是試圖同時使用幾種方法,這顯然行不通。所以我慢慢地構建一切,效率低下會讓某些程式員徹夜難眠,但這里是作業代碼:
var create_stylesheet = function(){
let to_return = [];
let first_line =
{
'selector': 'node', 'style': {'content': 'data(label)', 'background-color': 'BlueViolet'}
};
let second_line =
{
'selector': 'edge', 'style': {'label': 'data(score)'}
};
let last_line = {
'selector': ':selected',
'style': {
'background-color': 'SteelBlue', 'line-color': 'black', 'target-arrow-color': 'black', 'source-arrow-color': 'black'}
};
//Push the first two line into the array.
to_return.push(first_line);
to_return.push(second_line);
for(let 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}
};
to_return.push(to_append); //Push each line into the array.
}
to_return.push(last_line); //add the last line.
return to_return;
}
uj5u.com熱心網友回復:
有兩點需要注意。
- 在 for 回圈中,您需要
let i = 0. - 然后,您可以連接并回傳。
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(let 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}
};
to_return = to_return.concat(to_append);
}
return to_return;
}
create_stylesheet()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/490930.html
標籤:javascript json 迭代
