优化精简这段代码 currentStoreDistance() { const { longitude, latitude, big_stores } = this.data const stores = big_stores const origin = `${longitude},${latitude}` const destination = `${stores.longitude},${stores.latitude}` const that=this this.data.myAmapFun.getDrivingRoute({ origin, destination, success(data) { stores.distance = Math.round(data.paths[0].distance / 100) / 10 that.setData({ big_stores:stores }) } }) }

时间: 2024-02-13 10:06:37 浏览: 21
可以优化的地方有: 1. 将 destructuring 和赋值合并成一行; 2. 不需要将 `big_stores` 赋值给 `stores`,直接使用 `big_stores` 即可; 3. 将 `const that = this` 改为箭头函数; 4. 使用对象解构简化 `data.paths[0].distance` 的访问; 5. 使用模板字符串简化字符串拼接。 优化后的代码如下: ``` currentStoreDistance() { const { longitude, latitude, big_stores } = this.data; const origin = `${longitude},${latitude}`; const destination = `${big_stores.longitude},${big_stores.latitude}`; this.data.myAmapFun.getDrivingRoute({ origin, destination, success: (data) => { const { distance } = data.paths[0]; big_stores.distance = Math.round(distance / 100) / 10; this.setData({ big_stores }); } }); } ```
相关问题

优化以下代码 if (ConfigsData.ContainsKey("BUOY_LIST")) { //二级变量,存储BUOYLIST里面的所有数据 JsonData jsondataMessage = ConfigsData["BUOY_LIST"]; for (int i = 0; i < jsondataMessage.Count; i++) { JsonData message = jsondataMessage[i]; BUOY buoy = new BUOY() { BUOY_NAME = message.GetStringValue("BUOY_NAME"), LONGITUDE = message.GetDoubleValue("LONGITUDE"), LATITUDE = message.GetDoubleValue("LATITUDE"), IN_SCREEN = message.GetBoolValue("IN_SCREEN"), CAMERA_POSITION_X = message.GetDoubleValue("CAMERA_POSITION_X"), CAMERA_POSITION_Y = message.GetDoubleValue("CAMERA_POSITION_Y"), CAMERA_POSITION_Z = message.GetDoubleValue("CAMERA_POSITION_Z"), CAMERA_ROTITION_X = message.GetDoubleValue("CAMERA_ROTITION_X"), CAMERA_ROTITION_Y = message.GetDoubleValue("CAMERA_ROTITION_Y"), }; if (jsondataMessage[i].ContainsKey("IS_RED_COLOR")) { buoy.IS_RED_COLOR = message.GetBoolValue("IS_RED_COLOR"); } BUOY_LIST.Add(buoy); } }

以下是对代码的优化建议: 1. 将字符串常量提取为常量或者变量,避免多次使用字符串常量时的性能损失。 2. 使用 TryGetValue 方法来获取字典中的值,避免重复访问字典。 3. 将循环中的 jsondataMessage[i] 提取为变量,避免多次重复访问。 4. 对于包含可选字段的情况,使用 TryGetValue 方法来获取可选字段的值。 优化后的代码如下所示: ``` const string BUOY_LIST_KEY = "BUOY_LIST"; if (ConfigsData.TryGetValue(BUOY_LIST_KEY, out var buoyListData)) { foreach (var buoyData in buoyListData) { var buoy = new BUOY() { BUOY_NAME = buoyData.GetStringValue("BUOY_NAME"), LONGITUDE = buoyData.GetDoubleValue("LONGITUDE"), LATITUDE = buoyData.GetDoubleValue("LATITUDE"), IN_SCREEN = buoyData.GetBoolValue("IN_SCREEN"), CAMERA_POSITION_X = buoyData.GetDoubleValue("CAMERA_POSITION_X"), CAMERA_POSITION_Y = buoyData.GetDoubleValue("CAMERA_POSITION_Y"), CAMERA_POSITION_Z = buoyData.GetDoubleValue("CAMERA_POSITION_Z"), CAMERA_ROTITION_X = buoyData.GetDoubleValue("CAMERA_ROTITION_X"), CAMERA_ROTITION_Y = buoyData.GetDoubleValue("CAMERA_ROTITION_Y"), }; buoyData.TryGetValue("IS_RED_COLOR", out buoy.IS_RED_COLOR); BUOY_LIST.Add(buoy); } } ```

优化这个方法 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() 方法,我们可以更加优雅地处理异步操作,并使得代码更加简洁易懂。

相关推荐

优化精简这段代码// pages/Stores/Stores.js // 请求封装 import request from '../../utils/request' // 高德地图 import amapFile from '../../libs/amap-wx.130' // 地图实例 var myAmapFun Page({ data: { map: [] }, onLoad(options) { console.log(options) const that = this wx.createWACode({ path: '/pages/index/index', width: 430, scene: 'custom_value' }).then(res => { // 在页面中显示生成的小程序码 this.setData({ qrcodeUrl: res.path }); }).catch(err => { console.error(err); }); myAmapFun = new amapFile.AMapWX({ key: '5409c5fd8a9d2c7dfecef1faa8cd3ffc' }); wx.getLocation({ type: 'wgs84', isHighAccuracy: true, success(res) { that.setData({ latitude: res.latitude, longitude: res.longitude, speed: res.speed, accuracy: res.accuracy }) request( '/stores/stores', {}, 'POST').then(res => { that.setData({ map: res.data, }) that.calculateDistance() }) } }) }, // 计算附近门店距离 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) }).catch(err => { console.error(err); }); }, onShareAppMessage() { return { title: '分享标题', path: '/pages/index/index?custom_param=custom_value' }; } })

// 分页 handleSizeChange(val) { this.pageSize = val this.handleNodeClick() }, handleCurrentChange(val) { this.page = val this.handleNodeClick() }, async getTreeListList() { const { data } = await businessTreeApi() this.departlist = JSON.parse(data.data) }, // 右侧上部分信息 async handleNodeClick(type) { console.log(type) if (type) { this.id = type.id } const List = (await businessApi(this.id)).data.data // this.datalist.agentId = type.id ? type.id : id // console.log(this.datalist) // const {data}= await courierPagingApi(this.datalist) // console.log(data); console.log(List) if (List.type === 1) { this.form.type = '一级转运中心' } else if (List.type === 2) { this.form.type = '二级转运中心' } else this.form.type = '营业部' this.form.number = List.id // v-model 数字 // this.form.type=List.type==3?'营业部':'', // 类型 this.form.name = List.name // 名字 this.form.region = List.province.name // 省 this.form.city = List.city.name // 城市 this.form.county = List.county.name // 县区 this.form.address = List.address // 详细地址 this.form.people = List.managerName // 负责人 this.form.phone = List.phone // 电话 this.form.longitude = List.longitude // 经度 this.form.latitude = List.latitude // 维度 // ------------------------------------ let obj = { page: this.page, pageSize: this.pageSize, agencyId: this.id } // 页码 const { data } = await getUserPageApi(obj) this.total = data.data.counts console.log(data.data) this.tableData = data.data.items this.total = Number(data.data.counts) // 下拉框数据 const res = await editAreasApi() console.log(res) this.economize = res.data.data if (this.value) { const ress = await editAreasApi(this.value) console.log(ress) } }, onSubmit() { this.isOk = !this.isOk } // 编辑数据 }

geodetic_to_gauss_trans(double lon, double lat, int zone_mode, double custom_longitude) { if ((lon >= -180 && lon <= 180) && (lat >= -90 && lat <= 90) && (zone_mode == -1 || zone_mode == 0 || zone_mode == 1) && (custom_longitude >= -180 && custom_longitude <= 180)) { switch (zone_mode) { case 1: if (lon >= 1.5) { zone_ = int((lon + 1.5) / 3); central_meridian_ = zone_ * 3; } if (lon < 1.5) { zone_ = int((lon + 1.5) / 3) + 120; central_meridian_ = zone_ * 3 - 360; } break; case -1: if (lon >= 0) { zone_ = int(lon / 6) + 1; central_meridian_ = zone_ * 6 - 3; } if (lon < 0) { zone_ = int(lon / 6) + 60; central_meridian_ = (zone_ * 6 - 3) - 360; } break; case 0: central_meridian_ = custom_longitude; break; } } else { x_ = 0; y_ = 0; return false; } std::string proj_string = "+proj=tmerc +lat_0=0 +lon_0=central_meridian +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs +type=crs"; std::string to_replace = "central_meridian"; std::string replace_with = std::to_string(central_meridian_); size_t pos = proj_string.find(to_replace); proj_string.replace(pos, to_replace.length(), replace_with); PJ_CONTEXT *C = proj_context_create(); PJ *P = proj_create(C, proj_string.c_str()); PJ *G = proj_crs_get_geodetic_crs(C, P); PJ_AREA *A = nullptr; const char *const *options = nullptr; PJ *G2P = proj_create_crs_to_crs_from_pj(C, G, P, A, options); PJ_COORD c_in{}; c_in.lpzt.z = 0.0; c_in.lpzt.t = HUGE_VAL; c_in.lp.lam = lon; c_in.lp.phi = lat; PJ_COORD c_out = proj_trans(G2P, PJ_FWD, c_in); x_ = c_out.enu.n; y_ = c_out.enu.e; // PJ_COORD c_inv = proj_trans(G2P, PJ_DIRECTION::PJ_INV, c_out); std::cout.precision(20); std::cout << std::fixed; std::cout << x_ << "," << y_ << std::endl; std::cout << std::fixed << c_inv.lp.lam << "," << c_inv.lp.phi << std::endl; proj_destroy(P); proj_destroy(G); proj_destroy(G2P); proj_context_destroy(C); return true; }

最新推荐

recommend-type

基于MySQL+Vue.js开发集成实时聊天系统的动态项目管理web端源码+答辩PPT+使用说明.zip

基于MySQL+Vue.js开发集成实时聊天系统的动态项目管理web端软件源码+答辩PPT+使用说明.zip 【优质项目推荐】 1.项目代码功能经验证ok,确保稳定可靠运行。欢迎下载使用!在使用过程中,如有问题或建议,请及时私信沟通,帮助解答。 2.项目主要针对各个计算机相关专业,包括计科、信息安全、数据科学与大数据技术、人工智能、通信、物联网等领域的在校学生、专业教师或企业员工使用。 3.项目具有丰富的拓展空间,不仅可作为入门进阶,也可直接作为毕设、课程设计、大作业、项目初期立项演示等用途。 4.如果基础还行,或热爱钻研,可基于此项目进行二次开发,DIY其他不同功能。 基于MySQL+Vue.js开发集成实时聊天系统的动态项目管理web端软件源码+答辩PPT+使用说明.zip 部署前端服务 1. 打包前端文件生成 dist 文件夹 ```js // genal-chat-client npm i npm run build ``` 1. 将 dist 下所有文件放到 nginx 下的 html 文件夹中 2. 配置 nginx 的 gzip (提高传输速度)和请求级别(注意只是新增下面的代码,不是替换整个nginx文件) ```js 记得重启一下nginx #### 数据库配置 1. 安装 mysql 2. 设置 mysql 账号密码 3. 创建名为 `chat` 的数据库 4. 配置后端 `app.module.ts` 中的 mysql 账号密码 部署后端服务 1. 安装 pm2 ```js // genal-chat-server npm i pm2 -g ``` 2. 生成 dist 文件 ```js // genal-chat-server npm i npm run build ``` 3. 使用 pm2 运行 ```js // genal-chat-server npm run pm2 ```
recommend-type

Django学习资源3333

Django学习资源
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

MATLAB柱状图在信号处理中的应用:可视化信号特征和频谱分析

![matlab画柱状图](https://img-blog.csdnimg.cn/3f32348f1c9c4481a6f5931993732f97.png) # 1. MATLAB柱状图概述** MATLAB柱状图是一种图形化工具,用于可视化数据中不同类别或组的分布情况。它通过绘制垂直条形来表示每个类别或组中的数据值。柱状图在信号处理中广泛用于可视化信号特征和进行频谱分析。 柱状图的优点在于其简单易懂,能够直观地展示数据分布。在信号处理中,柱状图可以帮助工程师识别信号中的模式、趋势和异常情况,从而为信号分析和处理提供有价值的见解。 # 2. 柱状图在信号处理中的应用 柱状图在信号处理
recommend-type

解释这行代码 c = ((double)rand() / RAND_MAX) * (a + b - fabs(a - b)) + fabs(a - b);

这行代码是用于生成 a 和 b 之间的随机数。首先,它使用 rand() 函数生成一个 [0,1) 之间的随机小数,然后将这个小数乘以 a、b 范围内的差值,再加上 a 和 b 中的较小值。这可以确保生成的随机数大于等于 a,小于等于 b,而且不会因为 a 和 b 之间的差距过大而导致难以生成足够多的随机数。最后,使用 fabs() 函数来确保计算结果是正数。
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

MATLAB柱状图在数据分析中的作用:从可视化到洞察

![MATLAB柱状图在数据分析中的作用:从可视化到洞察](https://img-blog.csdnimg.cn/img_convert/1a36558cefc0339f7836cca7680c0aef.png) # 1. MATLAB柱状图概述** 柱状图是一种广泛用于数据可视化的图表类型,它使用垂直条形来表示数据中不同类别或组别的值。在MATLAB中,柱状图通过`bar`函数创建,该函数接受数据向量或矩阵作为输入,并生成相应的高度条形。 柱状图的优点在于其简单性和易于理解性。它们可以快速有效地传达数据分布和组别之间的比较。此外,MATLAB提供了广泛的定制选项,允许用户调整条形颜色、
recommend-type

contos如何测试http

Contos可以使用各种工具来测试HTTP,以下是一些常用的方法: 1. 手动测试:使用浏览器、Postman等工具手动发送HTTP请求,并检查响应是否符合预期。 2. 单元测试:使用测试框架编写单元测试,测试HTTP API的输入输出是否正确。 3. 集成测试:使用自动化测试框架编写集成测试,测试整个HTTP系统的功能和性能是否正常。 4. 压力测试:使用压力测试工具对HTTP系统进行负载测试,测试系统在高并发和高负载情况下的性能表现。 5. 安全测试:使用安全测试工具对HTTP系统进行安全测试,测试系统是否存在漏洞和安全隐患。 无论使用哪种方法,都需要根据具体情况选择合适的工具