سؤال

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