onLoad: function (options) { var lent = [ "https://wx.qlogo.cn/mmhead/XtxAEvJhLWZbe5xLnXFw1EjI54NkntBricIbfBkvNiajE/64" , "https://wx.qlogo.cn/mmhead/XtxAEvJhLWZbe5xLnXFw1EjI54NkntBricIbfBkvNiajE/64" , "https://wx.qlogo.cn/mmhead/XtxAEvJhLWZbe5xLnXFw1EjI54NkntBricIbfBkvNiajE/64" ] var temp = [] for ( var i = 0; i < lent.length; i++) { wx.downloadFile({ url: lent[i], success(res) { if (res.statusCode === 200) { temp[i] = res.tempFilePath } } }) } console.log(temp) } |
典型的闭包问题,可以通过立即函数或是forEach写箭头函数来解决。
for
(
var
i = 0; i < lent.length; i++) {
let index = i
wx.downloadFile({
url: lent[index ],
success(res) {
if
(res.statusCode === 200) {
temp[index ] = res.tempFilePath
}
}
})
}
显示出来,为啥
console.log(temp[0])
输出 undefined
异步的问题,你要写到temp[index] = res.tempFilePath 这一行后面console.log
1