I’m trying to populate this list with strings from the object data. It comes out as ‘undefined’. It’s the reference to the data object that doesn’t work. Why?
JS
data = [
{"q":"How much?", "ac":"20%", "a1": "1%", "a2": "10%", "a3": "5%"},
{"q":"What", "ac":"Ball", "a1": "Stone", "a2": "Bierd", "a3": "Carl"},
{"q":"When?", "ac":"1999", "a1": "2000", "a2": "2001", "a3": "2002"}
];
var q=0
window.onload = function() {
var ids =['a','b','c','d'];
var ans =['a1','a2','a3','ac'];
for (var j=0; j < ids.length; j++) {
var a = ans[j];
document.getElementsByClassName(ids[j])[0].innerHTML = data[q].a; //[<-- PROBLEM HERE]
};
}
HTML
<ul class="answers_quiz">
<li class="a"></li>
<li class="b"></li>
<li class="c"></li>
<li class="d"></li>
</ul>
You need to use the square bracket syntax rather than the dot syntax to use a variable as a property accessor:
The dot syntax looks for a property named “a” in
data[q]. Since there is no such thing, it returnsundefined. When you use the array notation, it looks for a property named whateveracontains.For example, on the first iteration, when
a === "a1",data[q].a1is equivalent todata[q][a].