如何解决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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。