我从我的API获取数据,如下所示:
function getWeight (username) {
/* This function takes a username as a parameter,
then it calls the API URL using the username
so that it gets the weights of that particular
user.
*/
var weights;
$.ajax({
type: 'GET',
url: '/weight/api/get_weight_data_admin/'+username,
dataType: 'json',
async: false,
success: function (data) {
weights = data
}
});
getWeightPlots(weights);
}
当我执行console.log(权重)时,上面的代码按预期工作,它正好显示了我的期望:
问题出在下面的代码中;我在下面的函数中创建的列表,并在while循环中向其追加值,在退出while循环后,我看不到它中的值。
function getWeightPlots (weights) {
/**
* This function takes a list of dictionaries, which contain
* dates when the weight was entered and the weight itself.
* It returns a list of weights that can be used for plotting on
* the graph.
*/
var weightList = [];
// get the last 12 months
var months = getMonths();
var numWeights = weights.length;
var i = 0;
var y = 0;
while (y < months.length) {
var weightMonthNum = weights[i]
weightMonthNum = weightMonthNum['date']
weightMonthNum = weightMonthNum.split('-');
weightMonthNum = parseInt(weightMonthNum[1])
var monthNum = monthToMonthNum(months[y])
if (weightMonthNum < monthNum){
i++;
}
else if (weightMonthNum == monthNum) {
weightList.push(1);
i++;
y++;
}
else {
y++;
weightList.push(0);
}
}
console.log(weightList);
}
我试过调试,一切似乎都运行正常,任何想法?
当调用getWeightPlots
时,weights
为空(未定义)。等待ajax完成然后在success
方法中调用它。