2014-07-19 87 views
3

我下面一个教程,建议检查的对象是字符串,而不是空的,如下:检查如果对象是字符串在Javascript

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

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

我试着用一些SO questionsherehere too !!

有相似(typeofinstanceof)其他可用的方法来测试它,所以我决定测试它的js斌:jsbin code here如下:

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 !!"); 
} 

现在我的问题是:

1-为什么当字符串使用为空字符串校验失败???

2-为什么instanceof检查失败?

+0

'如果(string2.charAt)'只检查方法是否定义,空字符串仍然是一个字符串,所以将返回true – charlietfl

+0

@charlietfl plz引用adeneo的答案,他说:“一个简单的字符串不是一个对象,它是一个主要的数据类型,并且没有原型,与用新String创建的String对象相反。“ – stackunderflow

+0

所以空字符串定义为文字不会返回true如果检查charAt函数的存在 – stackunderflow

回答

8

字符串值字符串对象(这就是为什么所述的instanceof失败)。

要使用“类型检查”来覆盖这两种情况,它将是typeof x === "string" || x instanceof String;第一只匹配字符串和后者匹配字符串

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

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


对于字符串,数字和布尔的原始值有字符串,数字和布尔的对应对象类型,分别。当在这些原始值之一上使用x.property时,效果为ToObject(x).property - 因此为“促销”。这在ES5: 9.9 - ToObject中讨论。

null或未定义的值都没有相应的对象(或方法)。函数已经是对象,但有一个历史上不同且有用的结果typeof。对于不同类型的值,请参阅ES5: 8 - Types。字符串类型,例如,表示字符串值。

2

1-为什么当字符串为空时使用string2.charAt检查字符串失败?

下面的表达式评估为假,因为第一条件失败:

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中,字符串可以是文字或对象。例如:

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

但是:

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

您可以可靠地告诉我们,如果它是一个字符串,通过检查两个类型和instanceof

str instanceof String || typeof str === "string"; 
+0

你错过了一些东西,我的问题是没有把参数设置为0。实际上没有括号。'if(str ing1 && string1.charAt){' – stackunderflow

相关问题