I have a for loop that adds properties to the data object
words is an array of strings
for (let i = 0; i < words.length; i++) {
let word = words[i];
data[word] = i;
}
After that, my objext looks like this:
data = {"the": 0, "of": 1, "and": 2, "to": 3, "a": 4, …};
I have tried
data['the'];
but it returns undefined
How do I retrieve the value of the property?
Here is my full code
let vocab = {};
$.ajax({
url: "10000words.txt",
success: function(data) {
data = data.split(/\n/).slice(0, 10000);
for (let i = 0; i < data.length; i++) {
let word = data[i];
vocab[word] = i;
}
console.log(vocab['test']);
}
});
When I type vocab into the console, it prints out vocab but when I try vocab['the'] it returns undefined
data['the']works fine. You're doing something else wrong. Please provide an stackoverflow.com/help/mcvevocaboutside the ajax function?vocaboutside thesuccesscallback, not whether you’ve declared it outside. Your issue is impossible to reproduce, if you didn’t actually accessvocaboutside ofsuccess. That’s why I think the most likely issue is this: Why is my variable unaltered after I modify it inside of a function? - Asynchronous code referenceconsole.log([...Object.keys(vocab).find((word) => /t[^a-z]*h[^a-z]*e/.test(word))]);and see whether it matches["t", "h", "e"]. There may be invisible characters within your words, thusvocab.thewon’t work.