Reputation: 6554
I am trying to do a lesson, learning javascript objects and so forth... I am having a problem with this for in loop and I suppose the object literal itself
var darkness = {
add: function(a,b) {
for(var title in b) {
alert(a+ " is the "+ b.title );
alert(a+ " holds many of"+b.dream);
}
}
};
darkness.add('darkness',{
title :'feelings',
dream:'dreams'
});
This alerts twice? test http://jsbin.com/ogunor/1/edit
Can someone help me learn these a little better
Upvotes: 0
Views: 39
Reputation: 1919
Your code is alerting twice beacuse you are looping through every property (title
and dream
) in the b
object.
This is enough:
var darkness = {
add: function(a,b) {
alert(a+ " is the "+ b.title );
alert(a+ " holds man of " +b.dream);
}
};
darkness.add('darkness',{
title :'feelings',
dream:'dreams'
});
Upvotes: 2
Reputation: 15366
I will try to explain. The b
object you pass has two properties: title and dream. your for(var title in b)
loop, will go over each of the object properties key.. meaning will run twice - the first iteration will have title = 'title'
and the second title='dream'
. In each iteration you alert twice - thus getting 4 alerts. You can remove the loop completely only keeping the alerts for it to alert only twice.
var darkness = {
add: function(a,b) {
for(var title in b) { // runs twice cuz you have 2 properties
alert(title); // try alerting title just to see what it hold in each iteration.
alert(a+ " is the "+ b.title );
alert(a+ " holds many of"+b.dream);
}
}
};
darkness.add('darkness',{
title :'feelings', // 1st property
dream:'dreams' // 2nd property
});
Upvotes: 2