const addr = this.deliveryData.map(item => `${item.province + '-'}${item.city + '-'}${item.area + '-'}${item.contact_address}`) 优化这段代码
时间: 2024-02-27 21:54:04 浏览: 21
这段代码可以用模板字符串来简化:
```
const addr = this.deliveryData.map(item => `${item.province}-${item.city}-${item.area}-${item.contact_address}`);
```
使用模板字符串可以使代码更简洁易读。
相关问题
async getData() { const {data:ret} = await this.$http.get('yearCount') this.allData = ret // console.log(ret); this.updataChart() }, updataChart() { const sellerValues = this.allData.map((item) => { return item.value }) const sellerNames = this.allData.map((item) => { return item.name })报错chart1.vue:64 Uncaught (in promise) TypeError: this.allData.map is not a function,怎么解决?
这个错误的原因是 `this.allData` 不是一个数组,而是一个 undefined 或者其他类型的值。你可以在调用 `updataChart()` 方法之前,先确保 `this.allData` 已经被赋值为一个正确的数组。或者在 `updataChart()` 方法中,先进行一个类型判断,避免在非数组类型上调用 `map()` 方法。例如:
```
updataChart() {
if (!Array.isArray(this.allData)) {
console.error('this.allData is not an array')
return
}
const sellerValues = this.allData.map((item) => {
return item.value
})
const sellerNames = this.allData.map((item) => {
return item.name
})
// ...
}
```
优化这个方法 calculateDistance(){ const that=this const mapVar=JSON.parse(JSON.stringify(that.data.map)) mapVar.forEach(item=>{ const origin=that.data.longitude+','+that.data.latitude const destination=item.longitude+','+item.latitude myAmapFun.getDrivingRoute({ origin: origin, destination: destination, success: function(data){ item.distance=Math.round(data.paths[0].distance/100)/10 }, }); }) that.setData({ map:mapVar }) console.log(this.data.map) console.log(Date()) }
这个方法中使用了异步操作,因此我们需要等所有异步操作完成后才能更新数据并显示结果。我们可以使用 Promise.all() 方法来等待所有异步操作完成后再更新数据。
下面是优化后的代码:
```javascript
calculateDistance() {
const that = this;
const mapVar = JSON.parse(JSON.stringify(that.data.map));
const promises = [];
mapVar.forEach(item => {
const origin = that.data.longitude + ',' + that.data.latitude;
const destination = item.longitude + ',' + item.latitude;
const promise = new Promise((resolve, reject) => {
myAmapFun.getDrivingRoute({
origin: origin,
destination: destination,
success: function(data) {
item.distance = Math.round(data.paths[0].distance / 100) / 10;
resolve();
},
fail: function(err) {
reject(err);
}
});
});
promises.push(promise);
});
Promise.all(promises).then(() => {
that.setData({
map: mapVar
});
console.log(that.data.map);
console.log(Date());
}).catch(err => {
console.error(err);
});
}
```
在上面的代码中,我们使用了 Promise.all() 方法来等待所有异步操作完成后再更新数据。具体来说,我们将所有异步操作的 Promise 对象存储在一个数组中,并使用 Promise.all() 方法来等待这些异步操作完成后执行回调函数。
在每个异步操作的回调函数中,我们使用 resolve() 方法来指示该异步操作已完成,并将返回的数据保存到 mapVar 数组中。在所有异步操作完成后,我们使用 setData() 方法来更新数据并显示结果。
另外,我们还使用了 Promise 的错误处理机制来处理异步操作失败的情况,并在 catch() 方法中输出错误信息。
总的来说,通过使用 Promise.all() 方法,我们可以更加优雅地处理异步操作,并使得代码更加简洁易懂。