获取有关带有split和子字符串的字符串的一些信息

Get some information on a string with split and substring

本文关键字:字符串 信息 split 获取      更新时间:2023-09-26

我必须从字符串filePos中获取纬度和经度的信息。我必须把这些信息放入一个数组(称为海滩),所以它必须是:

var beaches = [
                  ["45.411158", "11.906326", 1]// 1 is the index
                  ["45.411190", "11.906324", 2]// 2 is the index
              ]

我试着这么做,但eclipse显示了这个错误:

"未捕获类型错误:无法读取未定义"的属性"length"

var filePos = "{'Data':'17/02/2015', 'Descrizione':'PROVA AAA', 'Lat':'45.411158', 'Lng':'11.906326', 'Foto':'sdjahvas'}" +
            "{'Data':'18/02/2015', 'Descrizione':'PROVA BAA', 'Lat':'45.411190', 'Lng':'11.906324', 'Foto':'asde'}";
var beaches = filePos.split("}") // Break up the original string on `", "`
.map(function(element, index){
    var temp = element.split(', ');
    lat = temp[2].substr(7, temp[2].length -2);
    lng = temp[3].substr(7, temp[3].length -2);
    return [lat, lng, index + 1];
}); 
console.log(beaches);
alert(JSON.stringify(beaches));

如果将对象字符串更改为有效的json并对其进行解析,则可以对对象进行迭代。

var jsonString = filePos.replace(/''/g, '"').split('}'),
    positionAry;
jsonString.pop();
positionAry = JSON.parse('[' + jsonString.join('},') + '}]');
beaches = positionAry.map(function (obj) {
    return [obj.Lat, obj.Lng];
});