我得到了这段代码,它会将File.txt的所有内容调用到变量fileContent中。如何让它只获得一个指定的行号而不是整个文件内容?
var xhr = new XMLHttpRequest();
xhr.open("GET","data/File.txt",false);
xhr.send(null);
var fileContent = xhr.responseText;
答案 0 :(得分:2)
您可以按行结束字符
拆分响应文本// fileContent now constain an array of strings
// where every item is a line
var fileContent = xhr.responseText.split('\n');
var lineNumber = 0;
var lineContent = fileContent[lineNumber]; // the content of the first line
// total number of lines
var linesCount = fileContent.length;
// random integer between 0 (minimum index) and linesCount - 1 (maximum index)
var randomLineNumber = Math.floor(Math.random() * linesCount);
var randomLineContent = fileContent[randomLineNumber];
答案 1 :(得分:0)
按换行符拆分文件并获取所需的行号:
const lineNumber = 42;
const myLine = fileContent.split('\n')[lineNumber];
或者让它更具可重复性:
const getLine = (content, lineNumber) => content.split('\n')[lineNumber];
getLine(fileContent, 42);
您执行错误处理。