我正在做这样的循环:
for (var index in data)
{
console.log(index);
$http.post('server.php')
.success(function(data, status)
{
console.log(index);
}
}
第一个console.log()
显示:0,1,2,3,4,5
第二个console.log()
显示:5,5,5,5,5,5
我真的不知道为什么。是因为我使用了名为data
的2个变量吗?我尝试重命名一个,但它没有解决问题。
答案 0 :(得分:1)
使用
Closures
,关闭中定义的功能会记住'创建它的环境。 [From docs]
for (var index in data) {
(function(index) {
$http.post('server.php')
.success(function(data, status) {
console.log(index);
});
})(index);
}

答案 1 :(得分:1)
您需要在此方面使用 Closures 。关闭,"打包" 索引的值,稍后在回调时执行。
for (var index in data) {
(function(index) {
$http.post('server.php')
.success(function(data, status) {
console.log(index);
});
})(index);
}
答案 2 :(得分:0)
封闭。如果很难理解它基本上是这样做的:
function doPostCall(index) {
$http.post('server.php')
.success(function(data, status) {
console.log(index);
}
}
for (var index in data) {
console.log(index);
doPostCall(index)
}
看,它只是将帖子分成它自己的函数,它自己的索引变量保证不会从外部改变/