检查对象是否是Javascript中的字符串

时间:2014-07-19 19:13:59

标签: javascript string instanceof

我正在按照教程建议检查对象是否为字符串而不是空,如下所示:

var s = "text here";
if ( s && s.charAt && s.charAt(0))

据说如果s是字符串,那么它有一个方法charAt然后最后一个组件将检查字符串是否为空。

我尝试使用SO questions here 以及here too !!

所以我决定在Js Bin中测试它:jsbin code here如下:

typeof

现在我的问题是:

1-为什么使用instanceof ???

在字符串为空时检查字符串失败

2-为什么var string1 = "text here"; var string2 = ""; alert("string1 is " + typeof string1); alert("string2 is " + typeof string2); //part1- this will succeed and show it is string if(string1 && string1.charAt){ alert( "part1- string1 is string"); }else{ alert("part1- string1 is not string "); } //part2- this will show that it is not string if(string2 && string2.charAt ){ alert( "part2- string2 is string"); }else{ alert("part2- string2 is not string "); } //part3 a - this also fails !! if(string2 instanceof String){ alert("part3a- string2 is really a string"); }else{ alert("part3a- failed instanceof check !!"); } //part3 b- this also fails !! //i tested to write the String with small 's' => string // but then no alert will excute !! if(string2 instanceof string){ alert("part3b- string2 is really a string"); }else{ alert("part3b- failed instanceof check !!"); } 检查失败?

2 个答案:

答案 0 :(得分:9)

字符串值不是 String对象(这就是instanceof失败的原因) 2

使用"类型检查"来涵盖这两种情况。它将是typeof x === "string" || x instanceof String;第一个匹配字符串,后者匹配字符串

本教程假设[仅] String对象 - 或者提升 1 的字符串值 - 使用charAt方法,因此使用"duck-typing"。如果该方法确实存在,则调用它。如果charAt超出范围,则返回空字符串"",这是一个false-y值。

教程代码也接受一个" \ 0"的字符串,而s && s.length不会 - 但它也会"工作"在数组(或jQuery对象等)上。就个人而言,我信任调用者提供允许的值/类型,并使用尽可能少的类型检查"或尽可能使用特殊套管。


1 对于string,number和boolean的原始值,分别有相应的String,Number和Boolean对象类型。当x.property用于其中一个原始值时,效果为ToObject(x).property - 因此"促销"。这在ES5: 9.9 - ToObject中进行了讨论。

null或undefined值都没有对应的对象(或方法)。函数已经是对象,但具有历史上不同且有用的typeof结果。

2 有关不同类型的值,请参阅ES5: 8 - Types。字符串类型,例如,表示字符串值。

答案 1 :(得分:3)

  

1-为什么使用string2.charAt?

在字符串为空时检查字符串是否失败

以下表达式的计算结果为false,因为第一个条件失败:

var string2 = "";
if (string2 && string2.charAt) { console.log("doesn't output"); }

第二行基本上相当于:

if (false && true) { console.log("doesn't output"); }

例如:

if (string2) { console.log("this doesn't output since string2 == false"); }
if (string2.charAt) { console.log('this outputs'); }
  

2-为什么instanceof检查失败?

这失败了,因为在javascript中,string可以是文字或对象。例如:

var myString = new String("asdf");
myString instanceof String; // true

然而:

var myLiteralString = "asdf";
myLiteralString instanceof String; // false

通过检查类型和instanceof

,您可以可靠地判断它是否为字符串
str instanceof String || typeof str === "string";