为什么最终输出“B-D”

时间:2013-11-05 06:13:42

标签: javascript for-loop while-loop output

请记住,这是未完成的,我唯一的问题是为什么console.log会产生这个输出?

  

/> B / *这是我的预期* /

     

/> B-D / *第二个输出我预计只是“> / D”我对如何提出> /“B-D”* /

感到困惑
graphArray = ["4","A","B","C","D","A-B","B-D","B-C","C-D"];
pointsArray = [];
linesArray = [];
nodes = graphArray[0];
for (i = 1; i < graphArray.length; i++) {
    if (i <= nodes) {
    pointsArray.push(graphArray[i]);
    }
    if (i > nodes) {
        linesArray.push(graphArray[i]);
    }
}
nextpoint = pointsArray[0];
patt = new RegExp(/-.*/);
patt2 = new RegExp(nextpoint + "-");
for (i = 0; i < linesArray.length; i++) {
    x = 0;
    while (x < linesArray.length) {
        if (linesArray[x].replace(patt,"") === nextpoint) {
            nextpoint = linesArray[x].replace(patt2,"");
            console.log(nextpoint);
        }
        x++;
    }
}

编辑: Smacks额头它对我来说一定是太晚了我无法相信我错过了。谢谢你的意见。解决。

1 个答案:

答案 0 :(得分:1)

你的patt2 = new RegExp(nextpoint + "-");应该在循环中

for (i = 0; i < linesArray.length; i++) {
    x = 0;
    while (x < linesArray.length) {

        patt2 = new RegExp(nextpoint + "-");
        if (linesArray[x].replace(patt,"") === nextpoint) {
            nextpoint = linesArray[x].replace(patt2,"");
            console.log(nextpoint);
        }
        x++;
    }
}