【问题标题】:If / else statement in for loopfor循环中的if/else语句
【发布时间】:2020-07-20 20:30:31
【问题描述】:

我有一个从 Firebase 数据库收集位置的 for 循环。根据这些数据,我还计算出用户手机与其所在位置之间的距离。

如果找不到 userData,我的应用程序现在会中断,因此我想为不存在用户位置创建故障保护。但是我无法让它工作...... if AND else 语句中的两个 console.log 条目都不会被触发。我也没有看到“这是否有效”的外部评论。对我来说已经晚了,所以也许我错过了一些明显的东西?

for (const key in resData) {
    const reduxUserLocation = getState().locationActions.userLocation

    if (reduxUserLocation === null) {
    const calculateDistance = getDistance(
        { latitude: resData[key].location[0].lat, longitude: resData[key].location[0].lng },
        { latitude: reduxUserLocation.lat, longitude: reduxUserLocation.lng }
    )
    console.log('distance?' , calculateDistance)

    loadLocations.push(
        new ReportedLocations(
            key,
            resData[key].ownerId,
            resData[key].location,
            resData[key].description,
            resData[key].streetname,
            resData[key].placename,
            resData[key].date,
            calculateDistance
        )
    );
        }
        else {
            console.log("user location isn't found")
            const calculateDistance = 0

            loadLocations.push(
                new ReportedLocations(
                    key,
                    resData[key].ownerId,
                    resData[key].location,
                    resData[key].description,
                    resData[key].streetname,
                    resData[key].placename,
                    resData[key].date,
                    calculateDistance
                )
            );        
        }
        console.log('Does this work outside the if/else statement?')
}

【问题讨论】:

  • 你有一个语法错误,在 "console.log('user location is not found')" 周围更改每个双引号的单引号,它应该可以工作
  • 当看到,对我来说太晚了,我错过了那些 ;-) 没有解决问题,但谢谢!

标签: javascript react-native redux


【解决方案1】:

所以看起来你正在尝试从 reduxUserLocation 检索纬度/经度值,当它为空时

if (reduxUserLocation === null) {
    const calculateDistance = getDistance(
        { latitude: resData[key].location[0].lat, longitude: resData[key].location[0].lng },
        { latitude: reduxUserLocation.lat, longitude: reduxUserLocation.lng } // THIS LINE
    )

显然这是不可能的,而且会引发错误。因此,您在其下方看不到任何日志行。

此外,我认为您的 if 语句不正确。如果可能的话,您似乎想计算距离,否则它应该为 0。您的 if 语句正好相反。

除此之外,使用 for-in 循环时还有一个问题。最好总是检查 hasOwnProperty

如果您只想考虑附加到对象本身的属性,而不是其原型,请使用 getOwnPropertyNames() 或执行 hasOwnProperty() 检查(也可以使用propertyIsEnumerable())。或者,如果您知道不会有任何外部代码干扰,您可以使用检查方法扩展内置原型。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

这里是,我认为应该是正确的代码

for (const key in resData) {
  // Check if key is a property, if not, skip this iteration
  if (!resData.hasOwnProperty(key)) {
    continue;
  }

  const reduxUserLocation = getState().locationActions.userLocation;

  let calculateDistance = 0; // Set default distances to 0

  // If location is present, use that to calculate the distance and overwrite the variable above
  if (reduxUserLocation){
    calculateDistance = getDistance(
      {latitude: resData[key].location[0].lat, longitude: resData[key].location[0].lng},
      {latitude: reduxUserLocation.lat, longitude: reduxUserLocation.lng}
    );
  }
 
  // Moved push to array after the if-statement -> DRY (Don't Repeat Yourself)
  loadLocations.push(
    new ReportedLocations(
      key,
      resData[key].ownerId,
      resData[key].location,
      resData[key].description,
      resData[key].streetname,
      resData[key].placename,
      resData[key].date,
      calculateDistance
    )
  );
}

【讨论】:

  • 你是救生员麦克斯!我的代码现在可以按预期工作了,非常感谢!! ;-)
【解决方案2】:

如果不查看用于 Firestore 查询的代码,就很难进行调试。如果我不得不猜测,我会考虑使用对 SDK 的调用来检查空文档/查询,如 documentation 所示。我根据您的代码自定义了文档中的示例代码。

这里有一些用于读取单个文档的代码。

let resData;
const doc = await cityRef.get();
if (!doc.exists) {
  console.log('No such document!');
  resData = null
} else {
  resData = doc.data();
}

还有一个集合

let resDataArr = []
const snapshot = await citiesRef.where('capital', '==', true).get();
if (snapshot.empty) {
  console.log('No matching documents.');
  resDataArr = [null]
} else {
  snapshot.forEach(doc=> resDataArr.push(doc.data()) );
}

如果您使用的是库,这可能会发生变化。我没有测试这段代码,所以可能有一两个语法错误。

【讨论】:

  • 问题不在于 Firebase 查询。 resData 已填充并具有来自 Firebase 的所有信息以计算距离。问题在于 reduxUserLocation 为空(因为用户没有授予获取位置的权限)。因为 reduxUserLocation 为 null,calculateDistance 会抛出错误。所以我想如果 reduxUserLocation 设置了计算距离,如果不只是在任何地方设置一个距离为零。不知何故,我的代码中完全忽略了 if/else 语句。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-28
  • 1970-01-01
相关资源
最近更新 更多