Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Load array declaration from a text file in JavaScript

Before posting, I've read through suggested similar questions, but couldn't find an answer.

I have an array declaration stored in a text.txt file. Let's say the array declaration looks something like this:

["content1-1", ["content2-1", "content2-1"]]

I want to load this as an array into a variable in JavaScript.

This is what I tried:

var data = []
	function loadSOAFile(chineseCharacter) {
		var textfileFileName = "text.txt"
		var rawSOAFile=new XMLHttpRequest();
		rawSOAFile.open("GET",textfileFileName);
		rawSOAFile.onload=function(){
 			console.log(rawSOAFile.responseText);
			data = rawSOAFile.responseText
		}
		rawSOAFile.send();
		
		setTimeout(function() {
 document.getElementById("debuggingconsole").innerHTML = data[0]
 }, 200);
}

However, when I call the function, instead of writing "content1-1" it writes "[", so clearly it loads the variable as a string rather than an array.

Is there a cleaver way to load it as an array declaration? I don't deal with JS all that often, so answers providing a little bit more context would be most appreciated.

Answer*

Draft saved
Draft discarded
Cancel
3
  • This is brilliant. Thank you so much, works like a charm. Commented Sep 23, 2019 at 21:48
  • 1
    @Tyro if the answer solved your problem, please click to accept the answer. Commented Sep 23, 2019 at 22:24
  • I’ve just "ticked it off." I hope that’s what you meant by "accept the answer." Commented Sep 25, 2019 at 4:36

lang-js

AltStyle によって変換されたページ (->オリジナル) /