我试图为数组中的每个项执行一个函数,我知道闭包,并通过使用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
工作和其他功能不工作?!