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] + " ");
}
-
2@ThiefMaster: I wonder whether they keep the question mark key down or if they press it repeatedly. Apart from the wondering why they do one of those things at all. In any case, I can imagine the "crazy-grrrrrr-angry" face when they do it ...Sebastian Mach– Sebastian Mach2011年07月21日 09:31:39 +00:00Commented Jul 21, 2011 at 9:31
-
3@ThiefMaster "FEWER question marks please."skyfoot– skyfoot2011年07月21日 09:34:50 +00:00Commented Jul 21, 2011 at 9:34
-
Sorry, I'm tired and a bit frustrated. Programming is so articulate and void of emotion, but I felt the need to express a little.mowwwalker– mowwwalker2011年07月21日 09:35:44 +00:00Commented Jul 21, 2011 at 9:35
-
1BTW, w3schools is not a good reference : w3fools.comslaphappy– slaphappy2011年07月21日 09:39:17 +00:00Commented Jul 21, 2011 at 9:39
-
1Very true. If you look for good references to learn the JavaScript way of things I suggest -- most importantly -- the MDC docs (developer.mozilla.org/en/JavaScript), John Resig's blog -- head author of jQuery -- (ejohn.org/category/blog) and Douglas Crockford's website (javascript.crockford.com)FK82– FK822011年07月21日 09:53:51 +00:00Commented Jul 21, 2011 at 9:53
5 Answers 5
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.x would literally mean the x property (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.
Comments
You can access both Object literals as well as Arrays with the bracket operator in JavaScript. For Objects the bracket operator accesses a member of the Object by converting the value in the bracket to a String (if it is not a String) and checking if it is indeed a property (mdc).
Your second example suggests using an "associative Array" which is discouraged in JavaScript (link).
To answer your question: the standard way (imo) of writing a Map like structure -- i.e. an Object holding key-value-pairs -- to iterate over using a for-in loop is the Object literal; the standard way of writing a more traditional array is the Array Object.
var map = { "a": "string" , "b": 0 , "c": null } ;
for(key in map) console.log("(!!) map # " + key + " : " + map[key] ) ;
var list = ["string",0,null] ;
for(i = 0 ; i < list.length ; i++) console.log("(!!) list # " + i " : " + list[i] ) ;
Comments
JavaScript objects properties can be accessed both with object[key] and object.key (and some other ways, most probably). Just the way they work.
Your second example, an array is a special object but still an object.
http://bonsaiden.github.com/JavaScript-Garden/#object.general
"The properties of an object can be accessed in two ways, via either the dot notation, or the square bracket notation."
Comments
in js objects are asociative arrays, meaning that they are nothing but a collection of key-value pairs.
If you are confused about the brakets, don't be! Javascript object properties can be accesed via the "." or the "[]" construction:
var a = {key : 'val'};
alert(a['key'] === a.key);
In most cases they work the same.
It's just a matter of preferences and browser implementation (eg : firefox works faster with brackets, while chrome works faster with the dots).
There are situations, where the dot construcion will fail: supose you have an object which has a property named "some-key".
If you want to acces it with the dot notation : object.some-key, you will most certain get an error, because the code is being interpreted as aa difference between 2 values : object.some - key. In this case you should use the brackets : object['some-key'].
There are other cases too, where the key contains a special character such as .,,,;,\,*...etc that already has a interpretation in javascript.