如果缺少属性,angularjs会跳过对象

时间:2017-01-18 15:26:20

标签: javascript angularjs

我有一个过滤器,它可以查看数组中的对象,以查看对象的纬度和经度的距离是否在用户选择的范围内。但是,问题是某些对象根本没有纬度和经度属性,这会破坏过滤器。有没有办法去跳过"如果它没有lat和long那么在对象上?或者如果它的纬度和长度为0?

代码:

    function distanceFromFunc(distanceFrom) {

      var m;
      var n;
      var positionContainer = [];
      var docLat;
      var docLon;
      var rowIdFromObj;
      var rowObj;
      var rowsArray;

      if (distanceFrom === "1") {
        vm.selectedRadius = 1609.344 //1 mile
      } else if (distanceFrom === "2") {
        vm.selectedRadius = 3218.688 //2 miles
      } else if (distanceFrom === "5") {
        vm.selectedRadius = 8046.720 //5 miles
      } else if (distanceFrom === "10") {
        vm.selectedRadius = 16093.440 //10 miles
      } else if (distanceFrom === "20") {
        vm.selectedRadius = 32186.880 //20 miles
      } else if (distanceFrom === "50") {
        vm.selectedRadius = 80467.200 //50 miles 
      } else if (distanceFrom === "999999") {
        vm.selectedRadius = 0
      };

      //THE PROBLEM HERE IS THAT WHEN IT HITS A RECORD WITHOUT LAT AND LONG
      //THE FUNCTION BREAKS
      function filterByDist(value) {
        console.log("VALUE IS ------>" + JSON.stringify(value));
        var dist = distance(myLat, myLon, value.locations[0].Lat, value.locations[0].Long);
        if (dist <= distanceFrom) {
          console.log("the dist is: " + dist);
          return value
        };
      };

      var digestedArray = originalData2.filter(filterByDist)
      $scope.locatorGridData = digestedArray;

   }; //end func

我相信它在这一行上有所突破:var dist = distance(myLat, myLon, value.locations[0].Lat, value.locations[0].Long);

3 个答案:

答案 0 :(得分:1)

在进行距离法调用之前,只需进行一些检查:

function filterByDist(value) {
  if (value.locations[0].Lat && value.locations[0].Long) {
    var dist = distance(myLat, myLon, value.locations[0].Lat, value.locations[0].Long);
    if (dist <= distanceFrom) {
      return value
    }
  }
}

假设错误确实发生在您认为的地方,ofc!但看起来似乎有错误似乎是合理的。

答案 1 :(得分:1)

应该只能将违规行修改为:

var dist;
if (value.locations && value.locations.length &&
    value.locations[0].Lat && value.locations[0].Long){
    dist = distance(myLat, myLon, value.locations[0].Lat, value.locations[0].Long);
}

答案 2 :(得分:1)

以下代码检查是否:

  • valuevalue.locations已定义

  • LatLong存在

只有满足这些条件才会计算距离。

if(value && value.locations.length && value.locations[0].Lat && value.locations[0].Long) {
     // Calculate distance
}