我必须转换/变换“二维数组”中的“值字符串”。
字符串结构
original=LatLng(46.20467, 13.34764),LatLng(46.20467, 13.34767),LatLng(46.20467, 13.34772),LatLng(46.20469, 13.34782),LatLng(46.20471, 13.34786),LatLng(46.20492, 13.34842),LatLng(46.20499, 13.34865),LatLng(46.20502, 13.34888),LatLng(46.20502, 13.34909),LatLng(46.205, 13.34953),LatLng(46.20503, 13.34969),LatLng(46.20516, 13.34992),LatLng(46.20572, 13.35065),LatLng(46.20576, 13.35075),LatLng(46.20576, 13.3508),LatLng(46.20573, 13.35092),LatLng(46.20565, 13.35101)...
数组结构将是
LatLong_completo = [[46.20467, 13.34764],[46.20467, 13.34767],[46.20467, 13.34772],[46.20469, 13.34782],[46.20471, 13.34786],[46.20492, 13.34842],[46.20499, 13.34865],[46.20502, 13.34888],[46.20502, 13.34909],[46.205, 13.34953],[46.20503, 13.34969],[46.20516, 13.34992],[46.20572, 13.35065],[46.20576, 13.35075],[46.20576, 13.3508],[46.20573, 13.35092],[46.20565, 13.35101],[46.20523, 13.35124],[46.20515, 13.35132]...
实际上我成功地完成了它,使用以下代码:
sentences = original.replace(/['LatLng(']/g, ""); // remove LatLng(
sentences = sentences.replace(/[')']/g, ""); // remove )
sentences = sentences.replace(/[' ']/g, ""); // remove (
sentences += ','; // add , at the end
LatLong_base = new Array;
LatLong_completo = new Array;
// loop based on var length
for(i=0;i<sentences.length;i++){
//estrae Latitudine e Longitudine ed elimina i dati appena estratti
position = sentences.search(/,/); // find first comma in string
let Latitudine = sentences.substr(0, position); // using search result extract data
sentences = sentences.slice(position+1); // using search remove extracted data
position = sentences.search(/,/);
let Longitudine = sentences.substr(0, position);
sentences = sentences.slice(position+1);
// assegna i dati in formato numerico all'Array
LatLong_base.push(Number(Latitudine)); // 1st data (with number conversion) to array
LatLong_base.push(Number(Longitudine));// 2nd data (with number conversion) to array
// assegna il nuovo array all'array principale
LatLong_completo.push( LatLong_base); // dummy array to main array
// reset dummy array
LatLong_base=[]
}
存在最好且快速的解决方案吗?
谢谢
这是我会使用的解决方案:
let original = "LatLng(46.20467, 13.34764),LatLng(46.20467, 13.34767),LatLng(46.20467, 13.34772)";
// Split the string into individual LatLng strings
let latLngStrings = original.split(',');
// Initialize an empty array to store the result
let LatLong_completo = [];
// Iterate through the latLngStrings
latLngStrings.forEach((latLngString) => {
// Extract the coordinates from the string
let matches = latLngString.match(/\((.*),\s(.*)\)/);
if (matches) {
let lat = parseFloat(matches[1]);
let lng = parseFloat(matches[2]);
// Create a sub-array and push it to the resultArray
LatLong_completo.push([lat, lng]);
}
});
console.log(LatLong_completo);