I have a script that reads a JSON file then populates an array with the name property of each element.
HTML
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
var a = [];
var myMethod = function(){
$.ajax({
url : "numbers.json",
dataType : "json",
success : function(data){
for(i in data){
a.push(data[i].name);
}
}
});
}
myMethod();
console.log(a[2]); // console.log() returns "undefined"
</script>
JSON
[
{"name" : "One"},
{"name" : "Two"},
{"name" : "Three"},
{"name" : "Four"},
{"name" : "Five"}
]
I cant't access a specific index of this array. The console log always returns undefined. I've tried to add .then()
after my ajax call, but it doesn't work too.