编程新手求助:JavaScript读取TXT文件并存储为数组
Hey there! Let's work through this together. It sounds like you've already nailed the basics of using FileReader to display your text file's content—great job getting that far! Let's adjust your code to store the content in an array instead.
First, let's build on the code you already have. I'll assume your TXT file uses a common simple structure (like one item per line), but I'll also cover how to adapt this for other formats.
Step 1: Your HTML (keep or tweak slightly)
You probably already have something like this for file selection—we can keep it simple:
<input type="file" id="txtFileInput" accept=".txt"> <div id="arrayOutput"></div>
Step 2: Modify Your FileReader Logic
Here's how to update your FileReaderLogic.js to convert the text content into an array:
// Hook up the file input to our handler document.getElementById('txtFileInput').addEventListener('change', processTxtFile); function processTxtFile(e) { const selectedFile = e.target.files[0]; if (!selectedFile) return; // Exit if no file is picked const reader = new FileReader(); reader.onload = function(e) { // Get the full text content from the file const rawText = e.target.result; // Convert text to array—adjust the separator based on your file! // For line-separated items (most common simple structure): const contentArray = rawText .split('\n') // Split string into array at each newline .map(item => item.trim()) // Remove extra spaces/newlines from each item .filter(item => item); // Remove empty entries (from blank lines) // If your file uses commas instead, use rawText.split(',') instead of split('\n') // For semicolons: rawText.split(';') // Now you have your array! Let's test it console.log('Your content array:', contentArray); // Display it on the page too, so you can see it document.getElementById('arrayOutput').textContent = `Array content: ${JSON.stringify(contentArray)}`; }; reader.readAsText(selectedFile); // Read the file as plain text }
Key Customization Tips
- Line-separated items: The code above uses
split('\n')—perfect if each entry in your TXT is on its own line. Thefilterstep cleans up any blank lines that might be at the start/end of the file. - Comma/semicolon-separated items: Swap
split('\n')forsplit(',')orsplit(';')—just make sure your file doesn't have the separator inside individual items (if it does, you'd need a lightweight CSV parser, but this works for simple cases). - Trimmed content: The
map(item => item.trim())step removes extra spaces or trailing line breaks from each array entry—skip this if you need to preserve that whitespace.
A quick heads-up: Browsers don't let JavaScript auto-load files from the user's device without their explicit selection (it's a security rule), so you can't get around needing that file input picker. If your original uncompleted goal was something else, feel free to share more details!
内容的提问来源于stack exchange,提问作者fabro5

