开发技巧总结JS

回调函数无法获取外部for循环 index之解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

getDetail({ACT:"wxGetstyleinfo"}, function (json) {
// that.getAllBrand = json
// 下方json为后台返回的所有门店信息
for (var i = 0; i < json.length; i++) { // 遍历所有门店
that.temp = json // 把所有门店信息全局化

/**
* 下方函数通过给回调函数传参 的方式,
* 解决了原来在回调函数内 无法获取当前for循环索引的问题。
*
* 同时通过在 回调函数内再调用其他函数的方式(还需再加一个全局变量 => that.temp = json),
* 实现依次给门店添加属性
* **/
getAround({C: json[i].CIty,K:"万达广场"}, function (result,w){ // 获取每一门店所在的城市???此处的i即为每次for循环的i
// 并依据其所在城市 返回周边信息
var random = randomNum(0,9)
console.log(random);
function randomNum(min, max) {
return Math.floor(min + Math.random() * (max - min));
}
// 下方函数是 通过传入 每一门店的index(w) 随机商店名 经纬度信息
getName(that,w,result[random].name,result[random].lat,result[random].lng);
// 并且将商店名插入每一个门店中
},i) // 此处的i是为了追踪每一个门店
// 然后把 i 作为参数传入到回调函数,即为上方的 (w)
}
})

function getName(that,i,str,lat2,lng2) {

var lat1 = that.temp[i].RoomStyleLat
var lng1 = that.temp[i].RoomStyleLng

that.temp[i].distance = distance(lat1,lng1,lat2,lng2);
that.temp[i].recommend =str;
if(i==that.temp.length-1) { // 此句判断的意思是,当最后一个门店的属性添加完成后 再把数据给html
setTimeout(function () {
that.getAllBrand = that.temp
}, 0)
}
}