我写了一个名为 getRect的函数,构造并 return 一个数组。
getRect:function() {
let positions = []
for (let i = 0; i < dataArr.length; i++) {
let numPosition = wx.createSelectorQuery()
let select = numPosition.select('#p'+dataArr[i].num)
select.boundingClientRect(function (res) {
positions.push([res.left+(res.width/2),res.top+(res.height/2)])
// positions[i] = [[res.left+(res.width/2),res.top+(res.height/2)]]
})
numPosition.exec()
}
return positions
},
该数组可以被打印,但是无法遍历和使用。typeof类型为object,长度显示却为0
onLoad: function() {
let pos = this.getRect()
console.log(pos) //正常打印
console.log(typeof(pos)) //object
console.log(pos.length) //为0
}
select.boundingClientRect 这个方法是异步的,return positions的时候,其实数据并没有push到数组里
async getRect() {
let positions = [];
let promiseList = [];
for (let i = 0; i < dataArr.length; i++) {
promiseList.push(new Promise(resolve => {
let numPosition = wx.createSelectorQuery()
let select = numPosition.select('#p'+dataArr[i].num)
select.boundingClientRect(function (res) {
positions.push([res.left+(res.width/2),res.top+(res.height/2)]);
resolve()
// positions[i] = [[res.left+(res.width/2),res.top+(res.height/2)]]
})
numPosition.exec()
}))
}
await Promise.all(promiseList)
return positions;
}