我正在尋找從文本文件中拉出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();
任何幫助表示讚賞!
哪裏是你的洗牌代碼?目前,您只能獲取該文件並將其拆分爲一行數組。你最好的嘗試在哪裏? –
https://codeshare.io/Tehk5 –