首页 > 解决方案 > 对于数组中的每个数组

问题描述

我有这样的数组:

[[[37.1316, 56.01645], [37.15117, 55.99955], [37.14439, 55.98932], [37.14661, 55.96372], [37.18212, 55.95873], [37.20565, 55.96284], [37.21284, 55.9766], [37.26641, 55.97947], [37.26056, 55.99314], [37.18898, 56.02122], [37.16173, 56.01322], [37.1316, 56.01645]]]

如何使用 toFixed 获取数组 toFixed(2) 中的每个项目?

在输出上我需要这样:

[[[37.73, 55.87], [37.69, 55.89], [37.63, 55.89], [37.58, 55.91], [37.55, 55.90], [37.56, 55.94], [37.51, 55.94], [37.53, 55.90], [37.56, 55.89], [37.57, 55.86], [37.57, 55.83], [37.57, 55.82], [37.58, 55.79], [37.65, 55.78], [37.65, 55.80], [37.66, 55.82], [37.67, 55.83], [37.69, 55.84], [37.72, 55.85], [37.70, 55.86], [37.73, 55.87]]]

标签: javascriptarrays

解决方案


用于Array.prototype.map映射内部数组,并用于Number.prototype.toFixed您获得的各个解构浮点数。

用于Array.prototype.reduce累加运算的处理结果:

const arr = [
  [
    [37.1316, 56.01645],
    [37.15117, 55.99955],
    [37.14439, 55.98932],
    [37.14661, 55.96372],
    [37.18212, 55.95873],
    [37.20565, 55.96284],
    [37.21284, 55.9766],
    [37.26641, 55.97947],
    [37.26056, 55.99314],
    [37.18898, 56.02122],
    [37.16173, 56.01322],
    [37.1316, 56.01645]
  ]
];


const data = arr.reduce((acc, innerArray) => {
  const t = innerArray.map(
    ([first, second]) => [first.toFixed(2), second.toFixed(2)]
  );
  acc.push(t);
  return acc;
}, []);
console.log(data);


推荐阅读