[英]Why can't I access JS object properties?
I have the following function: 我有以下功能:
function getAggregateData(){
var sums = new Object();
$.getJSON("example.json.php", function(data) {
//for each month
c = 0;
$.each(data, function(key, val, index) {
//for each store
$.each(val, function(key2, val2, index2) {
if(c == 0){
sums[key2] = val2;
}
else{
sums[key2] += val2;
}
});
c++
});
})
return sums;
}
Which I then call as such: 然后我称之为:
var totals = getAggregateData();
But when I console log I am totally stumped: 但是当我控制日志时,我完全难过:
console.log(totals)
reveals an object like this: 揭示了这样一个对象:
store1 500
store2 900
store3 750
and so on and so forth...
but when I do console.log(totals['store1')
I get undefinded. 但当我做console.log(totals['store1')
我得不到了。
I have also tried console.log(totals.store1)
我也尝试过console.log(totals.store1)
and console.log(totals[0].store1)
和console.log(totals[0].store1)
I am having some type of issue of scope, or I am not creating the object I think I am. 我有一些范围的问题,或者我没有创建我认为我的对象。
It looks like the function would be returning an empty object since it's not waiting for the AJAX call to finish. 看起来该函数将返回一个空对象,因为它不等待AJAX调用完成。
If you tried doing console.log(totals.store1) on the last line inside your $.getJSON callback you'll probably get a result. 如果您尝试在$ .getJSON回调中的最后一行上执行console.log(totals.store1),您可能会得到一个结果。
You'll need to put any code that requires data from "example.json.php" inside a callback that only gets run after the AJAX call has returned. 您需要将任何需要来自“example.json.php”的数据的代码放在回调中,该回调仅在AJAX调用返回后运行。
Eg 例如
function getAggregateData(){
var sums = new Object();
$.getJSON("example.json.php", function(data) {
//for each month
c = 0;
$.each(data, function(key, val, index) {
//for each store
$.each(val, function(key2, val2, index2) {
if(c == 0){
sums[key2] = val2;
}
else{
sums[key2] += val2;
}
});
c++
});
processAggregateData(sums);
})
}
function processAggregateData(totals) {
console.log(totals.store1);
}
getAggregateData();
given: 给定:
{
"1": {
"store1": 2450,
"store2": 1060,
"store3": 310
},
"2": {
"store1": 2460,
"store2": 1760,
"store3": 810
}
};
This should work if you intend to add the results for each store. 如果您打算为每个商店添加结果,这应该有效。
/**
* This functions need to be called when we have the data
*/
function processSums(obj){
console.log(obj);
}
function getAggregateData(){
var sums = {};
$.getJSON("example.json.php", function(data) {
$.each(data, function() {
$.each(this, function(key, val, index){
sums[key] = sums[key] || 0;
sums[key] += val;
});
});
// 4910
processSums(sums);
});
return sums;
}
getAggregateData();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.