这个问题是从 [] 是 Array 的一个实例,但 "" 不是 String 的实例 派生而来。
考虑到:
有没有更简单、更短、更本地化的方法来做这件事,还是我必须创建自己的函数?
考虑到:
"" instanceof String; /* false */
String() instanceof String; /* false */
new String() instanceof String; /* true */
并且
typeof "" === "string"; /* true */
typeof String() === "string"; /* true */
typeof new String() === "string"; /* false */
如果我有一个变量abc
,想知道它是不是字符串类型,可以使用以下代码:
if(typeof abc === "string" || abc instanceof String){
// do something
}
有没有更简单、更短、更本地化的方法来做这件事,还是我必须创建自己的函数?
function isStr(s){
return typeof s === "string" || s instanceof String;
}
if(isStr(abc)){
// do something
}
new String()
吗?还是这只是一个理论问题? - zerkmstypeof s === "string"
гҖӮжҲ‘жҖҖз–‘иҝҷйҖҡеёёеҸҜд»ҘжӯЈеёёе·ҘдҪңпјҢеӣ дёәеҫҲе°‘жңүдәәдјҡжҳҺзЎ®ең°д»Һnew String()
еҲӣе»әдёҖдёӘеӯ—з¬ҰдёІеҜ№иұЎгҖӮ - jfriend00typeof
。使用instanceof
可能会出现罕见但潜在的问题。 - gray state is coming