[removed] using typeof to check if string

前端 未结 6 1928
萌比男神i
萌比男神i 2021-02-14 15:32

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

相关标签:
6条回答
  • 2021-02-14 16:03

    "string" is not the same as String. I've found one way to test typeof for string.

    if (typeof something === typeof "test") ...
    

    You can of course use "string" to compare to, but any actual String will do.

    0 讨论(0)
  • 2021-02-14 16:08

    this is the for in value to work for me

    for(var x in languages){

    if(typeof languages[x] === "string"){
        console.log(languages[x]);
    } else }
    
    0 讨论(0)
  • 2021-02-14 16:12

    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])   
      };
    
    };
    
    0 讨论(0)
  • 2021-02-14 16:15

    The below coding is also useful to perform only string value.By using variable to access the property list of abject after that by using it check the value is a NotANumber by using isNaN.The code given below is useful to you

    var languages = {
    english: "Hello!",
    french: "Bonjour!",
    notALanguage: 4,
    spanish: "Hola!"
    };
    
    // print hello in the 3 different languages
    for(a in languages)
    {
    if(isNaN(languages[a]))
    console.log(languages[a]);
    }
    
    0 讨论(0)
  • 2021-02-14 16:21

    That's because you're checking the key of the object. To check the actual value, you should be doing something like object[key]. Try this:

     var languages = {
            english: "Hello!",
            french: "Bonjour!",
            notALanguage: 4,
            spanish: "Hola!"
        };
    
    // print hello in the 3 different languages
    for(var hello in languages){
        var value = languages[hello];
        if (typeof value === "string"){
        console.log(value); 
        }
    }
    
    0 讨论(0)
  • Here is the answer: (use typeof and then the object name followed by the var in your for statement and test whether it is equal to "string")

    var languages = {
        english: "Hello!",
        french: "Bonjour!",
        notALanguage: 4,
        spanish: "Hola!"
    };
    
    // print hello in the 3 different languages
    for (var x in languages){
        if (typeof languages[x] === "string"){
            console.log(languages[x]);
        }
        else ;
    }
    
    0 讨论(0)
提交回复
热议问题