【问题标题】:Generate a string from an array in Javascript从Javascript中的数组生成字符串
【发布时间】:2020-06-26 13:06:25
【问题描述】:

我正在尝试根据字符串数组生成一个点文件。

edges =[["Source1" ,"interfaceA" , "high" , "Sink1" , "interfaceB" , "high"], 
        ["Source2" ,"interfaceC" , "high" , "Sink2" , "interfaceD" , "low"]]

我希望我的输出点文件数据看起来像:

digraph mydot {
    "Source1" -> "Sink1"
    [
       label=<<font color="green">interfaceA</font>--&gt;<font color="green">interfaceB</font>>
    ];
    "Source2" -> "Sink2"
    [
       label=<<font color="green">interfaceC</font>--&gt;<font color="red">interfaceD</font>>
    ];
}

我尝试了下面的代码,但返回类似 digraph unnamed {,,}

        let mydot ='digraph mydot {  ';
         mydot += edges.map(edge => {
           let sourceInterfaceColor = "red";
           let sinkInterfaceColor = "red";
        if (edge[2]=="high")
          sourceInterfaceColor ="green";
        if(edge[5]=="high")
          sinkInterfaceColor ="green";

        mydot +=`\
                        ${edge[0]} -> ${edge[3]} \
            [                                    \
               label=<<font color= \"${sourceInterfaceColor}\">\"${edge[1]}\"</font>--&gt;<font color=\"${sinkInterfaceColor}\">${edge[4]}</font>> \
            ];`
            .stripMargin});
        mydot +='}';

定义 mydot 以获得正确的有向图数据的正确方法是什么。

【问题讨论】:

    标签: javascript arrays string dot


    【解决方案1】:

    这是实现所需输出的简单方法。一般template literals enable multiline features

    const edges =[["Source1" ,"interfaceA" , "high" , "Sink1" , "interfaceB" , "high"], ["Source2" ,"interfaceC" , "high" , "Sink2" , "interfaceD" , "low"]]
    
    const edgeToString = edge => `
        "${edge[0]}" -> "${edge[3]}"
        [
           label=<<font color="green">${edge[1]}</font>--&gt;<font color="green">${edge[4]}</font>>
        ]
    `.trimEnd()
    
    const digraphToString = edges => `digraph mydot {${edges.map(edgeToString).join('')}\n}`
    
    console.log(digraphToString(edges))

    【讨论】:

    • 但是,我想传入 edge[2] 和 edge[5],根据接口值 "high" 或 "low" 来决定 color ="green" 还是 "red" ,而不是始终将其硬编码为“绿色”。是否可以定义一个 var sourceInterfaceColor 和 sinkInterfaceColor?
    猜你喜欢
    • 2011-05-07
    • 2012-08-16
    • 2016-05-06
    • 2018-07-26
    • 2019-10-10
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    相关资源
    最近更新 更多