3

I have this problem that I can't figure out how to determine if the object only has strings. I am trying not only to get help on figuring this out, but if someone has time, they could explain why their answer works, to help me learn. Thank you

function hasOnlyStrings(o) {
 for (var val in o) {
   var values = o[match];
     if (typeof values === 'string') {
        return true;
     } 
     else { return false; }
 }
}

var car = {
 name: 'corvette',
 fast: true,
 color: 'black'
}

var truck = {
 name: 'ford',
 color: 'blue'
}
pertrai1
  • 4,146
  • 11
  • 46
  • 71

2 Answers2

3

You're just testing the first value, not all of them.

function hasOnlyStrings(o) {
    for (var val in o) {
        var values = o[match];
        if (typeof values != 'string') {
            return false;
        } 
    }
    return true;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
2

I think you need

function hasOnlyStrings(o) {
    for (var prop in o)
        if (typeof o[prop] !== 'string')
            return false;
    return true;
}

Also consider using o.hasOwnProperty(prop) if you want to avoid checking properties inherited from prototype.

Oriol
  • 274,082
  • 63
  • 437
  • 513
  • 4
    Please put braces around your loop and if body. We should not promote bad programming style in answers. – Barmar Jun 07 '14 at 15:16
  • That would have to be `o[val]` instead of `o[i]` – Robby Cornelissen Jun 07 '14 at 15:17
  • o[val], what happen with you ;). – chfumero Jun 07 '14 at 15:17
  • @Barmar I don't think it's bad programming if used with appropriate indenting. – Oriol Jun 07 '14 at 15:19
  • The problem is that sometimes you later add another statement to the block. You indent it the same, and don't notice that there were no braces, so it's not actually in the body like you expect. – Barmar Jun 07 '14 at 15:20
  • @Barmar True. But I'll leave it without braces, otherwise our answers would be almost identical :) – Oriol Jun 07 '14 at 15:23
  • FYI: http://stackoverflow.com/questions/2125066/is-it-bad-practice-to-use-an-if-statement-without-brackets?lq=1 and http://stackoverflow.com/questions/359732/why-is-it-considered-a-bad-practice-to-omit-curly-braces?lq=1 – Barmar Jun 07 '14 at 15:27