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'
}
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With