產生原因
如果從后端回傳過來的陣列資料,進行遍歷的時候不在success回呼函式內,則會產生如下的資料格式,雖然其也是陣列格式,但是內部的值取不出來,給后臺也傳不過去,
[__ob__: Observer]
0: "http://localhost:5757/userImages/o-WF75fylWJY6vm_xRNYeNIpicOg/2020032123451074033.jpg"
1: "http://localhost:5757/userImages/o-WF75fylWJY6vm_xRNYeNIpicOg/2020032123451034889.jpg"
length: 2
nv_length: (...)
__ob__: Observer {value: Array(2), dep: Dep, vmCount: 0}
__proto__: Array
原因:其實跟__ob__: Observer這個屬性沒有多少關系,原因還是在于異步,因為wx.chooseImage是一個異步執行的函式,如果在另外一個函式中直接取得tempfileList的值進行遍歷的話,就會造成等不到回呼結束就完成遍歷,所以在陣列中__ob__: Observer屬性雖然監聽到了值,但是取不出來,
chooseImg(){
var that = this
wx.chooseImage({
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
count:3,
success:(res)=>{
console.log(res)
that.tempfileList = res.tempFilePaths
}
})
}
submitImg(filePath){
......
}
submit(){
this.tempfileList.map((item)=>{
that.submitImgs(item)
})
}
解決辦法
要在回呼函式內進行遍歷,這樣回呼函式回傳陣列資料的順序和執行遍歷的順序就會一致,因此就不存在異步操作所產生的問題
chooseImg(){
var that = this
wx.chooseImage({
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
count:3,
success:(res)=>{
console.log(res)
that.tempfileList = res.tempFilePaths
that.tempfileList.map((item)=>{
that.submitImg(item)
})
}
})
}
submitImg(filePath){
......
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/140911.html
標籤:JavaScript
上一篇:前端筆試、面試題 - JS
下一篇:解決異步的幾種實作方式
