[英]Is it ok to do a type-converting comparison when checking if something is a string?
由于typeof someVariable === string
对于使用new String()
实例化的typeof someVariable === string
不会返回true,可以这样做吗:
if(typeof someVariable == 'string') {
// do something
}
要确保比较也能捕捉到这些情况,还是这种比较会产生意想不到的副作用?
由于typeof someVariable ===字符串对于使用new String()实例化的字符串不会返回true,因此可以这样做:
没关系 ,但是对于字符串对象它不会为您提供true
,但是仍然为false
。 重要的不是==
vs. ===
,而是您要检查的内容。
如果要可靠地检查字符串基元和字符串对象,则:
if (Object.prototype.toString.call(someVariable) === "[object String]")
...就是你的做法。 之所以someVariable
是因为如果someVariable
是一个字符串对象,那么这就是Object.prototype.toString
保证为其返回的字符串。 如果someVariable
是字符串基元 ,则在thisArg
Function#call
是什么之前,将其用作Function#call
的thisArg
(宽松模式)或Object.prototype.toString
函数本身(严格模式)都会将其强制为字符串对象。 无论哪种方式,您都可以返回"[object String]"
。
有关此内容的更多信息(在我的博客上) : 说什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.