javascript - Javascript 获取子数组的第二个元素(用逗号分隔)
问题描述
我的控制器有一个输出数组,如下所示:
[
["48.85585695936588,2.317734961729684"],
["48.87234429654349,2.351466422300973"],
["48.85376742273335,2.3639977028185513"]
]
我想从这个坐标创建一个多边形,所以这个数据结构(数组):
这是我的代码:
for(var j = 0; j < output.length; j++) {
var points = [];
var quart = JSON.parse(output[j]['polygon']);
for (var i = 0; i < quart.length; i = i+2) {
points.push({
lat: parseFloat(quart[i]),
lng: parseFloat(quart[i+1])
});
}
我无法获得经度的值(逗号后的那个)......
谢谢你。
解决方案
一种方法如下:
// original array:
let twoDimensionalArray = [
["48.85585695936588,2.317734961729684"],
["48.87234429654349,2.351466422300973"],
["48.85376742273335,2.3639977028185513"]
],
// using Array.prototype.map() to iterate over the
// Array, returning a new Array (assigned to the
// variable):
coordsArray = twoDimensionalArray.map(
// using an Arrow function to pass the current
// Array into the function:
(coords) => {
// here we use destructuring to assign
// values to a and b; to do this we take the last
// (and only) entry of of the coords Array, and
// split on the comma character. The first element
// of the Array created by String.prototype.split(),
// we then use Array.prototype.map() - along with
// another Arrow function to iterate over the returned
// Array to convert the Strings to numbers, with
// parseFloat():
[a, b] = coords.pop().split(',').map((xy)=>parseFloat(xy))
// here we return an Object with named 'lat' and 'lng'
// properties, assigning the relevant values to each:
return {
'lat': a,
'lng': b
}
});
console.log(coordsArray);
参考:
推荐阅读
- vue.js - 如何在 vuejs 中使用 konvajs 连接 2 个对象?
- amazon-web-services - 使用 AWS Glue Crawler 指定 SerDe 序列化库
- .net-core - 如何从不同的程序集在 Automapper 中注册配置文件?
- intellij-idea - 更新到 2019.2 后,IntelliJ 文本看起来很大
- r - 来自网站的节点不会抓取内容
- asp.net - 我们可以在asp.net web api中使用表单身份验证模式吗
- c# - 没有`using`关键字打开和关闭文件的最佳方法是什么
- javascript - 为什么在调用的 React 函数组件中只使用 props?
- recursion - 如何递归调用存储在 Arc 中的闭包
>? - python - 将 np.array 数据添加到 pandas 数据框中的列后,我可以对其进行排序吗?