Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object only has strings detection

Tags:

javascript

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'
}
like image 969
pertrai1 Avatar asked Nov 25 '25 20:11

pertrai1


2 Answers

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;
}
like image 166
Barmar Avatar answered Nov 28 '25 16:11

Barmar


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.

like image 30
Oriol Avatar answered Nov 28 '25 17:11

Oriol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!