简体   繁体   English

for循环中的if/else语句

[英]If / else statement in for loop

I have a for loop that gathers locations from the Firebase Database.我有一个从 Firebase 数据库收集位置的 for 循环。 From this data I also calculate a distance between the users phone and the location it self.根据这些数据,我还计算了用户手机与其自身位置之间的距离。

My app now breaks if the userData is not found, so I would like to create a failsafe for if the user location isn't there.如果找不到 userData,我的应用程序现在会中断,因此我想为不存在用户位置创建故障保护。 However I am not able to get this to work...both the console.log entries from the if AND else statement aren't fired.但是我无法让它工作...... if AND else 语句中的两个 console.log 条目都不会被触发。 I also don't see the Does this work outside comment.我也没有看到“这是否有效”的外部评论。 It's late for me so maybe I'm missing something obvious?对我来说已经晚了,所以也许我错过了一些明显的东西?

 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?') }

It's hard to debug without seeing the code you use for the firestore query.如果不查看用于 firestore 查询的代码,就很难进行调试。 If I had to guess I would look into checking for empty documents/queries using calls to the SDK as shown in the documentation .如果我不得不猜测,我会考虑使用对 SDK 的调用来检查空文档/查询,如 文档中所示。 I customized the example code in the docs based on your code.我根据您的代码自定义了文档中的示例代码。

Here's some code for a single document read.这是单个文档读取的一些代码。

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

and a collection和一个集合

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()) );
}

This may change if you're using a library.如果您使用库,这可能会改变。 I didn't test this code so there may be a syntax error or two.我没有测试这段代码,所以可能有一两个语法错误。

So it appears you are trying to retrieve a lat/long value from reduxUserLocation when it is null因此,当它是 null 时,您似乎正在尝试从 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
    )

Obviously this is not possible and it would throw an error.显然这是不可能的,它会引发错误。 Therefor, you are not seeing any log lines below it.因此,您看不到它下面的任何日志行。

Furthermore, I believe your if-statement is incorrect.此外,我相信您的 if 语句是不正确的。 It seems like you want to calculate the distance if possible and else it should be 0. Your if-statement does the reverse.如果可能的话,您似乎想计算距离,否则它应该为 0。您的 if 语句正好相反。

Besides that, there is a catch when using a for-in loop.除此之外,使用 for-in 循环时还有一个问题。 Best to always check if hasOwnProperty最好总是检查 hasOwnProperty

If you only want to consider properties attached to the object itself, and not its prototypes, use getOwnPropertyNames() or perform a hasOwnProperty() check (propertyIsEnumerable() can also be used).如果您只想考虑附加到 object 本身而不是其原型的属性,请使用 getOwnPropertyNames() 或执行 hasOwnProperty() 检查(也可以使用propertyIsEnumerable())。 Alternatively, if you know there won't be any outside code interference, you can extend built-in prototypes with a check method.或者,如果您知道不会有任何外部代码干扰,您可以使用检查方法扩展内置原型。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Here is, what I believe should be the correct code这是,我认为应该是正确的代码

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
    )
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM