rakete rakete - 3 months ago 9
Javascript Question

How to pass the real value while iterate the loop?

I think the problem is really clear. This is my code:

// Add markers for each spot
for(var spot of spots) {

var spotId: number = +spot.id;
console.log(spotId);

// Add marker for current spot
L.marker([spot.latitude, spot.longitude], {icon: this.mapService.getSchoolIcon() })
.addTo(this.map)
.on('click', () => console.log('CLICKED: ' + spotId) );
}


And this is the output in the console if I click all pins:

1
2
3
4
CLICKED: 4
CLICKED: 4
CLICKED: 4
CLICKED: 4

Answer

Replacing var spotId with let spotId should fix the issue as it will make spotId a block scope variable.