以正确的顺序附加字符串

时间:2016-12-29 14:26:34

标签: javascript string

我有一个哈希表,其中包含两个主键下的值:SubjectQuery。每个Query可以包含多个Subject

例如

Query-blabla, Subject1-12, Subject2=13

我正在尝试构建一个包含每个Query个主题的字符串,并且需要用逗号,分隔,以便我可以将其插入到cvs文件中, coulmns。

一切都很好,我唯一的问题是粗线。

现在它看起来像这样:

subject,subject,query,subject,,subject,subject,query,subject,,subject...

需要:

subject, subject, query
subject,subject, query etc...

我有以下代码

for (var k = 0; k < keyToGeneDetailMappingGroupArray.length; k++)
{

    var isGroupContained = keyToGeneDetailMappingGroupArray[k].hasItem(currentKey);

    if (isGroupContained)
    {
        //Not relevent: Watch the data structures: sumElements += keyToGeneDetailMappingGroupArray[k].getItem(currentKey).length;
        sumElements += 1; 

        linescontentSubject = keyToGeneDetailMappingGroupArray[k].items[currentKey][0].Subject;
        linescontentQuery = keyToGeneDetailMappingGroupArray[k].items[currentKey][0].Query;

        databegin = linescontentQuery + "," + linescontentSubject;

        if(dataAll.includes(linescontentQuery))
        {
            dataAll = linescontentSubject + "," + dataAll + ",";
        } //this is the problem//
        else 
        {
            dataAll = dataAll + databegin + "\r";
        }

        index += Math.pow(2, k);
    }
}

1 个答案:

答案 0 :(得分:1)

在完成该行之前,您需要修剪尾随逗号

else {
    dataAll = dataAll.substring(0, dataAll.length - 2);
    dataAll = dataAll + databegin + "\r";
}

另一种更简洁的方法是使用数组代替字符串连接,并使用数组的 join 方法完成。

var dataLine = [];

for (var k = 0; k < keyToGeneDetailMappingGroupArray.length; k++){
    var isGroupContained = keyToGeneDetailMappingGroupArray[k].hasItem(currentKey);

    if (isGroupContained){
        //Not relevent: Watch the data structures: sumElements += keyToGeneDetailMappingGroupArray[k].getItem(currentKey).length;
        sumElements += 1; 

        linescontentSubject = keyToGeneDetailMappingGroupArray[k].items[currentKey][0].Subject;
        linescontentQuery = keyToGeneDetailMappingGroupArray[k].items[currentKey][0].Query;

        databegin = linescontentQuery + "," + linescontentSubject;

        if(dataLine.includes(linescontentQuery)){
            dataLine.splice(0, linescontentSubject); 
        }
        else {
            dataAll = dataLine.join(',') + databegin + "\r";
            dataLine = []; //reset the dataline
        }

        index += Math.pow(2, k);
    }
}