2016-03-03 16 views
0

我正在尋找從文本文件中拉出5個「隨機」行,而不重複任何。文本文件中的每一行都有html代碼,可以插入到側面菜單中。我已經閱讀了Fisher-Yates shuffle,但不知道如何將其與JavaScript結合使用。目前我正在使用以下編碼從文件中拉出單行1行:Javascript從文本文件中亂序數組

var request = new XMLHttpRequest(); 
request.onload = function() { 
    // get the file contents 
    var fileContent = this.responseText; 
    // split into lines 
    var fileContentLines = fileContent.split('\n'); 
    // get a random index (line number) 
    var randomLineIndex = Math.floor(Math.random() * fileContentLines.length); 
    // extract the value 
    var randomLine = fileContentLines[ randomLineIndex ]; 

    // add the random line in a div 
    document.getElementById('random-testimonial').innerHTML = randomLine; 
}; 
request.open('GET', 'content.txt', true); 
request.send(); 

任何幫助表示讚賞!

+1

哪裏是你的洗牌代碼?目前,您只能獲取該文件並將其拆分爲一行數組。你最好的嘗試在哪裏? –

+0

https://codeshare.io/Tehk5 –

回答

0

你只需要重複request.onload()五次的代碼,不是嗎? (除了附加到div html而不是設置它。)只需使用循環。您無需實施隨機播放:您正在使用的隨機(0..N-1)整數表達式就是您需要選擇隨機播放的所有內容。

儘管您可能想要防止重複。也許在append之前檢查一個子字符串匹配。

var request = new XMLHttpRequest(); 
request.onload = function() { 
    var i = 0; 
    // get the file contents 
    var fileContent = this.responseText; 
    // split into lines 
    var fileContentLines = fileContent.split('\n'); 

    var target = document.getElementById('random-testimonial'); 
    var targetHTML = target.innerHTML; 

    while (i < 5) { 
     // get a random index (line number) 
     var randomLineIndex = Math.floor(Math.random() * fileContentLines.length); 
     // extract the value 
     var randomLine = fileContentLines[ randomLineIndex ]; 

     // add the random line in a div if not duplicate    
     if (! targetHTML.contains(randomLine)) { 
      targetHTML += randomLine; 
      i += 1; 
     } 
    } 

    target.innerHTML = targetHTML; 
}; 
request.open('GET', 'content.txt', true); 
request.send(); 
+0

謝謝。是的,我需要防止重複的線路拉。我給了這個去,但立即收到一個javascript未被捕獲的錯誤: 'code' links.js:17 Uncaught TypeError:targetHTML.contains is not functionrequest.onload @ content.js:17 'code' –

+0

@UltraWebHosting:well ,這很奇怪。 '.innerHTML()'方法應該返回一個字符串,並且字符串有一個'.contains()'方法。檢查一下'targetHTML'在控制檯上給你的東西。你確定'id''隨機推薦'存在嗎?如果不是,'targetHTML'將會是'null'並導致錯誤。 – pyrocrasty

+0

這是我正在使用的: \t \t http://codeshare.io/Tehk5 –

0

you could try this. generate 5 random numbers between 1 and n (where n = fileContentLines.length) say n1, n2,n3,n4 and n5. Then you get your 5 lines as fileContentLines[n1] and so on... use this code snippet to generate 5 random numbers:

`var arr = [] 
while(arr.length < 5){ 
    var randomnumber=Math.ceil(Math.random()*n) 
    var found=false; 
    for(var i=0;i<arr.length;i++){ 
    if(arr[i]==randomnumber){found=true;break} 
    } 
    if(!found)arr[arr.length]=randomnumber; 
}`