gpt4 book ai didi

javascript - 如何在数组对象中插入元素

转载 作者:太空宇宙 更新时间:2023-11-04 15:57:38 26 4
gpt4 key购买 nike

给出以下响应:

response=[{"long":"long_value1","lat":"lat_value1","ts":"ts_value"},{"long":"long_value2","lat":"lat_value2","ts":"ts_value"},{"long":"long_value3","lat":"lat_value3","ts":"ts_value"},{"long":"long_value4","lat":"lat_value4","ts":"ts_value"}]

然后使用 API,我尝试下一步执行此操作,以便在响应中插入“地址”属性:

    for(var i in response){
$http.get(url(i)).success(function(response2){
response[i].address = response2.valueToassign;
});
}

我的问题是“address”属性仅插入到最后一个对象中,如下所示:

 response=[{"long":"long_value1","lat":"lat_value1","ts":"ts_value"},{"long":"long_value2","lat":"lat_value2","ts":"ts_value"},{"long":"long_value3","lat":"lat_value3","ts":"ts_value"},{"long":"long_value4","lat":"lat_value4","ts":"ts_value", "address":"address_value4}]

这个循环如何在数组的每个对象中插入“地址”?

最佳答案

您的代码的问题在于它是异步的,在循环执行之前
试试这个

        var responses = [{"long":"long_value1","lat":"lat_value1","ts":"ts_value"},{"long":"long_value2","lat":"lat_value2","ts":"ts_value"},{"long":"long_value3","lat":"lat_value3","ts":"ts_value"},{"long":"long_value4","lat":"lat_value4","ts":"ts_value"}]

function uploader(i){
if(i< responses.length)
{
$http.get(url).success(function(response2){
if(response2){
response[i].address = response2.valueToassign;
uploader(i+1)
}
else{
alert('resposnse output is blank');
uploader(i+1)
}
});

}
else{
console.log(response);
}
}
uploader(0)

关于javascript - 如何在数组对象中插入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42558213/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com