Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialjohnnyesper
5,935 PointsHow do I call all cities in one line?
Great WS, straight forward and easy to follow. How do I call all cities without calling one by one?
var City = function(name, state) {
this.name = name || 'Portland';
this.state = state || 'Oregon';
this.printMyCityAndState = function() {
console.log("My city is " + this.name + ", and my state is " + this.state);
};
};
portland = new City();
seattle = new City('Seattle', 'Washington');
salem = new City('Salem');
vancouver = new City('Vancouver', 'Washington');
portland.printMyCityAndState();
seattle.printMyCityAndState();
salem.printMyCityAndState();
vancouver.printMyCityAndState();
3 Answers
Chris Shaw
26,676 PointsHi johnnyesper,
You can store each City
instance within an array
and/or object
and then iterate over it as shown below.
Using an array
var cities = [
new City(),
new City('Seattle', 'Washington'),
new City('Salem'),
new City('Vancouver', 'Washington')
];
for (var c in cities) {
// c = numeric array id
// cities[c] = `City` instance
cities[c].printMyCityAndState();
}
Using an object (if you want key/value pairs for quicker identification)
var cities = {
portland: new City(),
seattle: new City('Seattle', 'Washington'),
salem: new City('Salem'),
vancouver: new City('Vancouver', 'Washington')
};
for (var c in cities) {
// c = key (city name)
// cities[c] = `City` instance
cities[c].printMyCityAndState();
}
Happy coding!
Matthew Smart
12,567 PointsA bit of code would help, it means we don't haver to watch the whole video to figure out what you mean
johnnyesper
5,935 PointsYour right. It's in the question now.
johnnyesper
5,935 PointsThanks