Reputation: 1635
I am reading the book "JavaScript for web designers" and I've come to this example:
var fullName = {
"first": "John",
"last": "Smith"
};
for (var name in fullName) {
console.log(name + ": " + fullName[name]);
}
The output is:
"first: John"
"last: Smith"
What I don't get is: where do I tell the program to get the string "first" and "last". I mean, cycling the object "fullName", I fail to see how "name" can be related to "first" and "last". I hope this is clear. Can you help? Many thanks!
Upvotes: 6
Views: 297
Reputation: 331
When you loop through an object, you iterate through the keys. The keys of this object are first
and last
. Refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in for more information.
Upvotes: 2
Reputation: 103
in the above code name
represent key of the object,
first and last are both keys in the object. and can be used to access the value in the object.
like in the first run of the loop it will be something like this
for("first" in fullName) {
console.log("first" + ": " + fullName["first"] //John);
}
Upvotes: 3
Reputation: 82287
A for..in
loop will iterate through the object's keys. If you use this on an array, then it (most browser engines) will convert the array into an object behind the scenes (read more on Dictionary Mode) and iterate the keys.
You can view the keys by using
var fullName = {
"first": "John",
"last": "Smith"
};
console.log(Object.keys(fullName));
And essentially the result of this call is then iterated. Keep in mind that using for..in
does not guarantee order of the key value pairs.
Upvotes: 3
Reputation: 32511
for..in
iterates over the keys of an object. You can then access an objects values by name using brackets.
var obj = {
a: 1,
b: 2,
c: 3
};
for (var key in obj) {
console.log('Key:', key);
console.log('obj[key] == obj["' + key + '"] == obj.' + key);
console.log('obj.' + key + ' == ' + obj[key]);
}
Upvotes: 12
Reputation: 3266
It's pretty simple to learn and/or understand. You're looping through all of the properties in the object fullName
. For each property, you're giving it the temporary name/alias of name
So you could change it to for (var anything in fullName)
and then in the body of the for loop you would reference each property by the name anything
like so:
for (var anything in fullName) {
// anything is an alias for the current property your on of the object you're looping through
console.log(anything + ": " + fullName[anything]);
}
Upvotes: 6