简体   繁体   中英

Is it ok to do a type-converting comparison when checking if something is a string?

Since typeof someVariable === string will not return true for strings that were instantiated with new String() , is it ok to do this:

if(typeof someVariable == 'string') {
  // do something
}

To make sure that the comparison will catch those cases as well, or will such a comparison have unintended side effects?

Since typeof someVariable === string will not return true for strings that were instantiated with new String(), is it ok to do this:

It's okay , but it won't give you true for string objects, it'll still be false . It's not the == vs. === that matters, it's what you're checking.

If you want to reliably check for both string primitives and string objects, then:

if (Object.prototype.toString.call(someVariable) === "[object String]")

...is how you do that. It works because if someVariable is a string object, that's the string that Object.prototype.toString is guaranteed to return for it. If someVariable is a string primitive , then either using it as the thisArg in a Function#call (loose mode) or the Object.prototype.toString function itself (strict mode) will coerce it to a string object before figuring out what it is. Either way, you get back "[object String]" .

More about this (on my blog) : Say what?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM