javascript - array.push(obj)失败
本文介绍了javascript - array.push(obj)失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
var list = [];//大的集合
$.each(that.categoryList, function(index,value){
$.ajax({
type: 'get',
url: that.getHotUrl,
data:{
category:value.id,
pageIndex:1,
pageSize:2,
token:token
},
dataType: 'json',
success: function(response){
if(response.code==200){
var obj = new Object(); //集合对象
obj.category_name=value.name;
obj.items = response.data.items;
console.log(obj);
list.push(obj);
}
},
error: function(err) {
console.log(err);
}
});
});
console.log(list);
循环调用接口拿到数据构建一个对象数组,console结果list为空,但obj都正确
解决方案
ajax是异步的
先执行的是console.log(list);
然后在执行console.log(obj);
setTimeout(function(){
console.log(list);
},100);
这篇关于javascript - array.push(obj)失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文