2013-01-13 86 views
0

這段代碼有什麼問題?我想做一些類似於循環鏈表的東西。javascript循環鏈表

<script type="text/javascript" charset="utf-8"> 
     function LinkedText(text, nextLinkedText) { 
      this.text = text; 
      this.next = nextLinkedText; 
      this.AsNext= function() { 
       this.text = this.next.text; 
       this.next = this.next.next; 
       return this; 
      } 
     } 

     var first = new LinkedText('first') 
     var last = new LinkedText('last', first); 
     first.next = last; 

     alert(first.text); //show 'firts' 
     alert(first.AsNext().text); //show 'last' 
     alert(first.AsNext().text); //show 'last' not 'first' why? 
     alert(first.AsNext().text); //show 'last' 
     alert(first.AsNext().text); //show 'last' not 'first' why? 
    </script> 

回答

1

重寫的GetNext:

this.GetNext = function() { 
    return this.next; 
} 

這是沒有意義的的GetNext重新分配this.text時,所有你想要的是獲得鏈接的節點和訪問它的文本

您可以使用它像這樣:

var i = 0   // avoid infinite loop below 
var maxruns = 10; // avoid infinite loop below 

var node = first; 
while(node){ 
    doSomethingWithNode(node); 
    node = node.GetNext(); 

    // avoid an infinite loop 
    i++; 
    if (i > maxruns) { 
     break; 
    } 
} 
+0

@ user1973846號你總是返回*此*,而不是* *旁邊的實例。而這種編程風格被廣泛認爲是不好的做法,因爲它違反了參考透明性原則http://en.wikipedia.org/wiki/Reference_transparency_(computer_science \)。你怎麼知道你現在在鏈表中的哪個位置?如果經過一些調用GetNext之後,你想在第一個元素之後有原始的下一個元素,它將會消失! – XORcist

+0

Thx。現在我明白了我的錯誤。在到達定義結構的末尾後,我回到我的第一個對象,因爲我重新分配了它。 – user1973846