Array forEach仅返回第一项

问题描述

我正在尝试在Array上使用forEach,但它仅适用于Array中的第一项。

我想返回对象列表,但不在数组中

这是我的数组

const latLngCoords = [   
  [-1.56789,63.45547],[-1.44523,63.48642],[-1.54635,63.46643]

];

然后我当前使用的forEach方法

let x;

latLngCoords.forEach(e => {
  x = { lat: e[0],lng: e[1] };
});

return x;

结果是

{ lat: -1.56789,lng: 63.45547 }

如预期

{ lat: -1.56789,lng: 63.45547 }
{ lat: -1.44523,lng: 63.48642 }
{ lat: -1.54635,lng: 63.46643 }

感谢您的帮助

解决方法

使用map返回新数组。

forEach只是遍历数组,但不返回新数组。

const latLngCoords = [   
  [-1.56789,63.45547],[-1.44523,63.48642],[-1.54635,63.46643],];

const result = latLngCoords.map(e => {
  return { lat: e[0],lng: e[1] };
});

console.log(result);

,

您可以使用map返回数据数组。

const x = latLngCoords.map(cord=>({lat:cord[0],lng:cord[1]}));
,

let x=[];
const latLngCoords = [   
  [-1.56789,63.46643]

];

latLngCoords.forEach((c) => {
      x.push({ lat: c[0],lng: c[1] })
})

console.log(x)

,

forEach只是简单地遍历数组,而不给您返回结果。您每次在forEach中都重新声明x变量。

只需在forEach中使用控制台日志:

latLngCoords.forEach(e => {
console.log({ lat: e[0],lng: e[1] });
});

或使用map制作新的对象数组:

let newArr = latLngCoords.map(e => ({ lat: e[0],lng: e[1] }));
console.log(newArr)
,

使用map代替forEach

const result = latLngCoords.map(([lat,lng]) => ({ lat,lng}));

const latLngCoords = [   
  [-1.56789,63.46643]

];

const result = latLngCoords.map(([lat,lng}));
console.log(result);