产生原因
如果从后端返回过来的数组数据,进行遍历的时候不在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){ ...... }