简体   繁体   English

在检查某些东西是否是字符串时可以进行类型转换比较吗?

[英]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: 由于typeof someVariable === string对于使用new String()实例化的typeof someVariable === string不会返回true,可以这样做吗:

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: 由于typeof someVariable ===字符串对于使用new String()实例化的字符串不会返回true,因此可以这样做:

It's okay , but it won't give you true for string objects, it'll still be false . 没关系 ,但是对于字符串对象它不会为您提供true ,但是仍然为false It's not the == vs. === that matters, it's what you're checking. 重要的不是== vs. === ,而是您要检查的内容。

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. 之所以someVariable是因为如果someVariable是一个字符串对象,那么这就是Object.prototype.toString保证为其返回的字符串。 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. 如果someVariable是字符串基元 ,则在thisArg Function#call是什么之前,将其用作Function#callthisArg (宽松模式)或Object.prototype.toString函数本身(严格模式)都会将其强制为字符串对象。 Either way, you get back "[object String]" . 无论哪种方式,您都可以返回"[object String]"

More about this (on my blog) : Say what? 有关此内容的更多信息(在我的博客上)说什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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