我正在使用getter函数get_beverages_data
将JSON对象的内容移动到对象的javascript数组中,因此我可以更好地传递和操作该数据。
在该getter函数中正确创建了数组(我从控制台调试中知道了这一点),但是当我从populate_lists
访问该getter函数时,得到的内容未被识别为数组。
代码
function get_beverages_data() {
var beverages = [];
$.ajax({
url: "data.json",
dataType: 'json',
type: 'get',
cache: false,
async: false, //note: this is for debugging purposes
success: function(data) {
$(data.beverages).each(function(index, value) {
var beverage = {name:value.name};
beverages.push(beverage);
});
console.log("First value in array (within get_beverages_data): " + beverages[0].name);
return beverages;
}
});
}
function populate_lists() {
var beverages_data = get_beverages_data();
console.log("First value in array (within populate_lists): " + beverages_data[0].name);
}
预期的控制台输出:
First value in array (within get_beverages_data): Rolling Rock
First value in array (within populate_lists): Rolling Rock
实际控制台输出:
First value in array (within get_beverages_data): Rolling Rock
Uncaught TypeError: Cannot read property '0' of undefined