React Native中forEach循环如何获取上一个/下一个位置数据?
解决JavaScript forEach遍历中获取前后元素的问题
嘿,这个问题我熟!forEach本身的回调函数默认只提供当前元素、索引和原数组这三个参数,所以没法直接拿到上一个或下一个元素,但咱们可以利用索引轻松解决这个问题,下面结合你的React Native代码给你两种可行方案:
方案一:利用forEach的索引参数获取前后元素
forEach的第二个参数是当前元素的索引,第三个参数是遍历的原数组,咱们可以通过索引的加减来访问前后元素,记得要做边界判断(避免第一个元素没有上一个、最后一个元素没有下一个的情况):
const locationsArray = Array.from(locations); locationsArray.forEach((item, index, arr) => { // 获取上一个元素,索引大于0时才存在 const prevItem = index > 0 ? arr[index - 1] : null; // 获取下一个元素,索引小于数组长度-1时才存在 const nextItem = index < arr.length - 1 ? arr[index + 1] : null; // 你的距离计算逻辑(这里注意:除以1000后单位是公里,要是想判断200米的话,要么去掉/1000,要么把条件改成>0.2) const distance = geolib.getDistance( { latitude: item.latitude, longitude: item.longitude }, { latitude: 35.75, longitude: 51.456 } ) / 1000; if (distance > 200) { console.log('longer than 200km'); } else { console.log('bala bala '); } // 现在可以自由使用前后元素了 if (prevItem) { console.log('上一个位置信息:', prevItem); // 比如计算当前位置和上一个位置的距离: // const distanceToPrev = geolib.getDistance(item, prevItem)/1000; } if (nextItem) { console.log('下一个位置信息:', nextItem); } });
方案二:改用for循环(更直观的边界控制)
如果你觉得forEach的索引判断有点绕,直接用普通的for循环会更直观,能清晰控制前后元素的访问:
const locationsArray = Array.from(locations); for (let i = 0; i < locationsArray.length; i++) { const item = locationsArray[i]; const prevItem = i > 0 ? locationsArray[i - 1] : null; const nextItem = i < locationsArray.length - 1 ? locationsArray[i + 1] : null; // 同样的距离计算逻辑 const distance = geolib.getDistance( { latitude: item.latitude, longitude: item.longitude }, { latitude: 35.75, longitude: 51.456 } ) / 1000; if (distance > 200) { console.log('longer than 200km'); } else { console.log('bala bala '); } // 使用前后元素 if (prevItem) { console.log('上一个位置:', prevItem); } if (nextItem) { console.log('下一个位置:', nextItem); } }
小提醒
你代码里的/1000会把米转换成公里,所以当前判断的是“超过200公里”,如果你的需求是判断200米的话,要么去掉这个除法,要么把条件改成> 0.2,别搞混单位哦~
内容的提问来源于stack exchange,提问作者Amir
相关产品推荐
相关产品推荐

