简体   繁体   English

使用嵌套的for和splice的Javascript

[英]Javascript using nested for and splice

I'm trying too look for points in a polygon. 我也在尝试在多边形中寻找点。

So I have an array with point-objects and an array with polygon-objects. 所以我有一个带有点对象的数组和一个带有多边形对象的数组。

I want to iterate over my points-array and than iterate over the polygon-array and look if the point is in that array. 我想遍历点数组,而不是遍历多边形数组,然后查看点是否在该数组中。 If the point is in the array I want to remove the point from the points-array because one point can only be in one polygon. 如果该点在数组中,我想从点数组中删除该点,因为一个点只能在一个多边形中。

So I tried to use this function: 所以我尝试使用此功能:

function pointsInPolygons(features, points) {
    var pointCopy = $.extend(true, [], points.features);
    for (var i = 0; i < pointCopy.length; i++) {
        var point = pointCopy[i];
        for (var j = 0; j < features.features.length; j++) {
            var feature = features.features[j];
            if (isPoly(feature) && gju.pointInPolygon(point.geometry, feature.geometry)) {
                feature.properties.ratings.push(point.properties.rating);
                pointCopy.splice(i, 1);
                i--;
            }
        }
    }
}

But after going through the inner for, the function is leaving. 但是经过内部for之后,该函数就离开了。 I tried the same without splice and decreasing i. 我尝试了同样的方法,但没有拼接并降低i。 But it is still the same behavior. 但是它仍然是相同的行为。

So the question is how can I get into the outer for again? 所以问题是我该如何再次进入外部?

Actually, you don't have to remove the item from the array, your current for loop against points will only iterate through once. 实际上,您不必从数组中删除该项目,当前针对points for循环只会迭代一次。 Here's a flatten approach to what you're doing. 这是您正在执行的扁平化方法。

function pointsInPolygons(features, points){
  let pointsCopy = points.features.slice();
  let check = (point,feature) => isPoly(feature) && gju.pointInPolygon(point.geometry, feature.geometry);
  let isInPolygon = point => features.find(check.bind(null, point));

  pointsCopy.forEach(point => {
    let feature = isInPolygon(point);
    if (!!feature) {
      feature.properties.ratings.push(point.properties.rating);
    }
  });
}

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

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