代码之家  ›  专栏  ›  技术社区  ›  Ibrahim Mohammed

函数不考虑闭包

  •  0
  • Ibrahim Mohammed  · 技术社区  · 6 年前

    我试图为数组中的每个项执行一个函数,我知道闭包,并通过使用ES6对此进行补偿 let 并尝试使用 forEach 如下所示:

           this.tourIDS = [];
             this.tours.forEach(tour => {
             this.tourIDS.push(tour.tour_id);
           });
    
           this.tourIDS.forEach(id => {
             this.map.setFilter('routes', ['==', 'tour_id', id]);
               console.log(id);
           });
    

    这是mapboxgl setFilter 接受如下查询参数的函数 ['==', 'tour_id', id] ,这里的想法是从 tourIDS 数组中包含的每个id一次。 因此,预期的行为是在数组中的每个元素上执行函数,但只有数组中的最后一个元素被执行,就像没有闭包一样 console.log(id) 在记录每个元素时正确执行,那么为什么 console.log 工作和其他功能不工作?!

    1 回复  |  直到 6 年前
        1
  •  0
  •   Ibrahim Mohammed    6 年前

    正如@Keith在评论中强调的那样,这不是循环的问题,而是mapbox gl js的本质问题 setFilter 调用该函数时,其本身会覆盖上一个过滤器。