简体   繁体   English

JavaScript leaflet map 的拆分阵列

[英]JavaScript Split array for leaflet map

I am trying to split a record within an array and put it again in an array.我正在尝试拆分数组中的记录并将其再次放入数组中。 Code is shown below.代码如下所示。

<script>
        var infras= <?= json_encode($infras); ?>; //[["Red Beach Seawall","1.3582,172.9266"],["Buota Bridge","1.3901,173.1343"]];

        var myStr = infras[0]; // "Red Beach Seawall","1.3582,172.9266"
        var strArray = myStr.split(",");

        // Display array values on page
        for(var i = 0; i < strArray.length; i++){
            document.write("<p>" + strArray[i] + "</p>");
        }
</script>

The outcome that I want is something like this.我想要的结果是这样的。

Red Beach Seawall红海滩海堤

1.3582,172.9266 1.3582,172.9266

In your code, myStr is an array and not a string.在您的代码中, myStr是一个数组而不是字符串。 You need to join it first.你需要先加入它。

Working code:工作代码:

 var infras= [["Red Beach Seawall","1.3582,172.9266"],["Buota Bridge","1.3901,173.1343"]]; var myStr = infras[0].join("|"); // "Red Beach Seawall|1.3582,172.9266" var strArray = myStr.split("|"); // Display array values on page for(var i = 0; i < strArray.length; i++){ document.write("<p>" + strArray[i] + "</p>"); }
 <body> </body>

And as HW Siew said, if your infras value is in JSON, then you need to run JSON.parse over it first to convert it into an array.正如 HW Siew 所说,如果您的基础设施值在infras中,那么您需要先运行JSON.parse以将其转换为数组。

if you data is a string, you need to first parse it into json.如果你的数据是一个字符串,你需要先把它解析成json。

 var infras= '[["Red Beach Seawall","1.3582,172.9266"],["Buota Bridge","1.3901,173.1343"]]'; // assuem you data is a string infras = JSON.parse(infras); infras.forEach( i => { document.write("<p>" + i[0] + "</p>"); document.write("<p>" + i[1] + "</p>"); })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM