I’m losing it here.. I am now extremely confused about how this loop works.
From w3 schools:
var person={fname:"John",lname:"Doe",age:25};
for (x in person)
{
document.write(person[x] + " ");
}
person is an object with properties right? How are those properties being accessed with the brackets? I thought that was for arrays?
Why does this also work, and shouldn’t it ONLY be like this?:
var person=[];
person["fname"] = "John";
person["lname"] = "Doe";
person["age"] = "25";
for (x in person)
{
document.write(person[x] + " ");
}
There are two ways in which you have access to an object’s properties:
obj.keyobj['key']The advantage of the second method is that you can also provide the key dynamically, e.g.
obj[x]in your example.obj.xwould literally mean thexproperty (i.e.obj['x']), which is not what you want.Arrays only work with brackets, but brackets are not limited to arrays. Arrays are under the hood also objects, but designed for numeric keys. You can still add properties with non-numeric keys to them, but that’s not what they are designed for.