I'm working on a codecademy.com exercise where we use for-in statements to loop through an object and print hello in different languages by checking to see if the values of the properties in the languages object are strings using typeof
my check to see if the value is a string is not working. my loops giving me this result
english
french
notALanguage
spanish
The code
var languages = {
english: "Hello!",
french: "Bonjour!",
notALanguage: 4,
spanish: "Hola!"
};
// print hello in the 3 different languages
for(var hello in languages){
var value = hello;
if (typeof value === "string"){
console.log(value);
}
}
These are the instructions for the exercise
Objects aren't so foreign if you really think about it!
Remember you can figure out the type of a variable by using typeof myVariable. Types we are concerned with for now are "object", "string", and "number".
Recall the for-in loop:
for(var x in obj) { executeSomething(); }
This will go through all the properties of obj one by one and assign the property name to x on each run of the loop.
Let's combine our knowledge of these two concepts.
Examine the languages object. Three properties are strings, whereas one is a number.
Use a for-in loop to print out the three ways to say hello. In the loop, you should check to see if the property value is a string so you don't accidentally print a number.
You are checking keys of the object, not the value. It's usually a good practice to check against the constructor of an object to determine its type.
Something like this:
var languages = {
english: "Hello!",
french: "Bonjour!",
notALanguage: 4,
spanish: "Hola!"
};
for(i in languages) {
if(languages[i].constructor === String) {
console.log(languages[i])
};
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With