I am trying to form a word list in Javascript, whereby each word is a key in the dictionary and the value is true. My program takes a word and and checks whether the word is a valid word in the list or not. The list of words is stored in a text file where words are separated by new line. I scan these words as a string and split the string to obtain an array of strings which consist of all words. Now I am unable to form the associative array from this array. Here is my code:
var dict={};
var words;
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
words=xmlhttp.responseText.split("\n");
for ( var i = 0; i < words.length; i++ ) {
dict[words[i]] = true; //This Section of Code not working
}
}
}
xmlhttp.open("GET","twl06.txt",true);
xmlhttp.send();
}
function check(str)
{
if(dict[str])
alert("Correct");
else
alert("Incorrect");
}
After doing a lot of tweaks with the code I have figured out that somehow the assosciative array is not being formed.
Here is the link to my full html/JS code: https://pastebin.com/2jwMcBfA
dict[words[i]] = true;
"does not work" and what do you even mean by does not work? The line looks correct, assuming thatwords
does indeed contain a list of words. Do you get any error? You have to provide more information. Do some basic debugging, inspect the values of the variables, etc.dict
before it was populated. Ajax is asynchronous, so the code following yourloadXMLDoc()
call is run before theonreadystatechange
handler is executed. Another problem could be that the words actually have leading or trailing white spaces. Make sure you useconsole.log
to inspect the data and notalert
.