Below are is a snippet of code containing object constructor and a function to populate an array of said objects. The populate function uses AJAX get() to consume data from a text file into an array. The array can be accessed and used from within the scope of the function; but my question is how can I use this array outside of the scope of the function? I have tried "initializing" the array globally and return the array from the function, which should be filled with objects. However, the array is empty when I try using it outside of the function's scope. This is odd to me because I am used to programming in C++. Any help would be greatly appreciated.
<script>
var file = "names.txt";
// object constructor
function person(first, middle, last) {
this.f_name = first;
this.m_name = middle;
this.l_name = last;
}
// populate object array
function populate() {
var people = [{}];
$.get(file, function(txt){
var records = txt.split("\n");
for(var i = 0; i < records.length; i++) {
var row = records[i].split("\t");
people[i] = new person(
row[0],
row[1],
row[2]
);
}
});
return people;
}
var arr = [{}];
arr = populate();
console.log(arr); //LOG: [object Object]
console.log(arr[666]); //LOG: undefined
console.log(arr[666].f_name); //SCRIPT5007: Unable to get
// value of the property
// 'f_name': object is null
// or undefined
</script>
答案 0 :(得分:0)
arr = populate();
//this is called and $.get would have not finished the execution.
$.get
is as asynchronous call.
but the console.log
statements will be executed before the arr
is filled.
Use success call function to do post implementation of success .
function populate() {
var people = [{}];
$.get(file, function(txt){
var records = txt.split("\n");
for(var i = 0; i < records.length; i++) {
var row = records[i].split("\t");
people[i] = new person(
row[0],
row[1],
row[2]
);
}
});
console.log(people); //LOG: [object Object]
console.log(people[666]); //LOG: undefined
console.log(people[666].f_name);
}