dynamic loop variable .each create hash javascript 1

dynamic loop variable .each create hash javascript

for (var i = 0; i < coords.length; ++i) {
    this["marker"+i] = "some stuff";
}

Here is what the above code is Doing:
1. It's creating a new object called "this"
2. It's creating a new property on that object called "marker0"
3. It's assigning the value "some stuff" to that property
4. It's repeating steps 2 and 3 for each value in the array
5. It's returning the object

So, if you have an array of coordinates like this:

var coords = [
{lat: 37.7833, lng: -122.4167},
{lat: 40.7127, lng: -74.0059},
{lat: 48.8567, lng: 2.3508}
];

And you call the function like this:

var markers = createMarkers(coords);

Then you'll get an object back that looks like this:

{
marker0: "some stuff",
marker1: "some stuff",
marker2: "some stuff"
}

You can then access the properties of that object like this:

markers.marker0
markers.marker1
markers.marker2

*/

function createMarkers(coords) {
var markers = {};
for (var i = 0; i < coords.length; ++i) { markers["marker" + i] = "some stuff"; } return markers; } var coords = [ {lat: 37.7833, lng: -122.4167}, {lat: 40.7127, lng: -74.0059}, {lat: 48.8567, lng: 2.3508} ]; var markers = createMarkers(coords); console.log(markers.marker0); console.log(markers.marker1); console.log(markers.marker2);

Similar Posts