I have created an object with 6 properties out of which first 3 properties are of string data type and the second 3 are of number data type. I decided to print the values of the properties of string data type alone. But my code is printing the values of all the properties available. The following is my code. Someone help me correct it.

var family = {
    dad: "Two",
    mom: "Twenty Two",
    kid: "Thirty Two",
    dadAge: 42,
    momAge: 41,
    kidAge: 12,

};

for(prop in family){
    if(typeof prop === "string"){
        console.log(family[prop]);
    }
}
有帮助吗?

解决方案

It should be if(typeof family[prop] === "string")

for(prop in family){
    if(typeof family[prop] === "string"){
        console.log(family[prop]);
    }
}

prop represents the key and its always "string" whereas you need to use family[prop] which will return you the value you have stored in the object

其他提示

prop will always be a string, since it contains the name of the property. You can do this:

for(prop in family){
    if(typeof family[prop] === "string"){
        console.log(family[prop]);
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top