2013-11-05 33 views
0

請記住,這是未完成的,唯一的問題是爲什麼console.log產生這個輸出?爲什麼最終輸出「B-D」

/> B/*這是我所期待的*/

/> BD/*第二輸出我預計將只是 「>/d」 我conused因爲它是如何來了與> /「BD」 */

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++; 
    } 
} 

編輯:嫌額頭它一定是太晚了我,我不能相信我錯過了。謝謝你指出。解決了。

+0

'patt2'是'/ A- /',所以它不會匹配 「B-d」,因此不會取代主導 「B-」。每次找到下一個點時,都必須構造一個新的正則表達式。我想你會在連字符上使用'substring'或者'split'獲得更好的性能。 – RobG

+0

使用'split'方法不是更容易嗎? – Thevs

回答

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++; 
    } 
}