JS中如何将LatLng格式字符串转为二维数组?求更优实现方案
坐标字符串转二维数组的优化方案
需求说明
需要将以下格式的坐标字符串:
original=LatLng(46.20467, 13.34764),LatLng(46.20467, 13.34767),LatLng(46.20467, 13.34772)...
转换为二维数组:
LatLong_completo = [[46.20467, 13.34764],[46.20467, 13.34767]...]
现有实现代码
我已经通过以下代码实现该功能:
sentences = original.replace(/['LatLng(']/g, ""); // 移除LatLng( sentences = sentences.replace(/[')']/g, ""); // 移除) sentences = sentences.replace(/[' ']/g, ""); // 移除空格 sentences += ','; // 在末尾添加逗号 LatLong_base = new Array; LatLong_completo = new Array; // 根据字符串长度循环 for(i=0;i<sentences.length;i++){ // 提取纬度和经度并移除已提取的数据 position = sentences.search(/,/); // 找到字符串中的第一个逗号 let Latitudine = sentences.substr(0, position); // 根据搜索结果提取数据 sentences = sentences.slice(position+1); // 移除已提取的数据 position = sentences.search(/,/); let Longitudine = sentences.substr(0, position); sentences = sentences.slice(position+1); // 将数据转为数值类型存入数组 LatLong_base.push(Number(Latitudine)); // 第一个数据转数值后存入数组 LatLong_base.push(Number(Longitudine));// 第二个数据转数值后存入数组 // 将新数组存入主数组 LatLong_completo.push( LatLong_base); // 将临时数组存入主数组 // 重置临时数组 LatLong_base=[] }
请问是否存在更高效、更简洁的实现方案?
更简洁高效的实现方案
可以利用正则表达式匹配每个LatLng()里的坐标对,结合数组链式调用快速转换,代码更简洁且性能更优:
// 先去除字符串开头的original=前缀 const cleanOriginal = original.replace(/^original=/, ''); // 匹配所有坐标对并转换为二维数组 const LatLong_completo = cleanOriginal // 匹配所有LatLng(纬度, 经度)格式的内容,捕获括号内的坐标部分 .match(/LatLng\(([^)]+)\)/g) // 逐个处理每个匹配项 .map(item => { // 移除LatLng()包裹,按逗号分割坐标,再转为数值类型 return item.replace(/LatLng\(|\)/g, '') .split(', ') .map(coord => Number(coord)); });
方案优势
- 代码更简洁:用链式调用替代复杂循环与多次字符串替换,可读性更强
- 性能更优:正则一次定位所有目标内容,避免循环中反复修改字符串的额外开销
- 逻辑更清晰:每一步仅做单一操作,从匹配到转换的流程一目了然
内容的提问来源于stack exchange,提问作者luca_papi
相关产品推荐
相关产品推荐

