【发布时间】:2014-01-20 16:14:51
【问题描述】:
我在使用 .push() 时遇到了一些问题。我相信问题在于我如何定义我的变量。基本上,变量“缓存”键与 JSON 中的 data.system[] 不对应。我正在尝试使用此(代码的缩写版本)将数字推送到现有数组:
var cache = ['cpu','mem'];
function doAjax() { /* toggled when ajax button pressed */
$.getJSON( "ajax.php", function(data) {
$.each(data.system, function(i, key) {
console.log(cache.i); /* undefined logged */
cache.i.push(key.value); /*Uncaught TypeError: Cannot call method 'push' of undefined */
});
});
}
JSON:
{
system: {
cpu: {
value: 1
},
mem: {
value: 330
}
}
}
Fiddle(我认为我没有正确设置 JSON 数据):http://jsfiddle.net/x9JaP/
【问题讨论】:
-
我在你的 json 结构中看不到数组。
-
我忽略了外面的 { }。 JSON 完美适用于其他代码领域。