Keith D Kaiser
Keith D Kaiser

Reputation: 1036

Javascript 'for of' loop not properly resolving to the value

I have a simple array that I'm trying to iterate over but I'm apparently not understanding the 'for of' JavaScript loop. The following code returns exactly has it should;

const callOBJb = ['KD0NBH0BJ','W0DLKOBJ','WA0TJTOBJ'];
        for (let i of callOBJb) {  
            console.log(i);
        }

return: KD0NBHOBJ W0DLKOBJ WA0TJTOBJ

But the following code errors out with; "TypeError: i.getCenter is not a function. (In 'i.getCenter()', 'i.getCenter' is undefined)" because the variable 'i' does not resolve to one of the above.

for (let i of callOBJb) {
       var Omiddle = i.getCenter(); 
    }

When I manually type the variable in such as;

var Middle = W0DLKOBJ.getCenter();

It works just fine. What am I not understanding about how this should work? I don't think I can use the ForEach here at least I'm not having any more luck than the for...of.

I was asked what the resolved variable for W0DLKOBJ might look like.

alert(JSON.stringify(KD0NBHOBJ));
 {"_southWest":{"lat":39.204385,"lng":-94.60714},"_northEast":{"lat":39.20646,"lng":-94.60481}}

Upvotes: 1

Views: 254

Answers (4)

Keith D Kaiser
Keith D Kaiser

Reputation: 1036

The solution came in how I received the data from PHP to start with. When I changed the definition to; const callOBJb = <?php echo "[$callOBJb]" ?> to include the square brackets and then used; for (let val of callOBJb) {...etc all of the variables resolved properly.

Upvotes: 0

Keith D Kaiser
Keith D Kaiser

Reputation: 1036

I went back to the php and redesigned the output to make conversation to Javascript easier. By doing that I was able to iterate through the values using "for (let val of callOBJb)" successfully.

Upvotes: 0

Yves Kipondo
Yves Kipondo

Reputation: 5603

The callOBJb variable is an Array of strings, and when you use for..of statement to perform a loop iteration, for each item in your iterable object you will get item at deposition corresponding to the time to loop bloc code is execute.

In you case as all items in the callOBJb array is simple string, javascript String.prototype Object doesn't define a function named getCenter that is the reason why you are getting

"TypeError: i.getCenter is not a function. (In 'i.getCenter()', 'i.getCenter' is undefined)

let callOBJb = ['KD0NBH0BJ','W0DLKOBJ','WA0TJTOBJ'];

for(let item of callOBJb){
  console.log(typeof item, item);
}

As you can see on each iteration the typeof item is always string.

Upvotes: 1

David
David

Reputation: 218930

This works:

var Middle = W0DLKOBJ.getCenter();

because this:

W0DLKOBJ

is different from this:

'W0DLKOBJ'

If the array should contain the variable values and not string literals, don't use quotes:

const callOBJb = [KD0NBH0BJ, W0DLKOBJ, WA0TJTOBJ];

Upvotes: 5

Related Questions