我下面一个教程,建议检查的对象是字符串,而不是空的,如下:检查如果对象是字符串在Javascript
var s = "text here";
if (s && s.charAt && s.charAt(0))
有人说,如果s是字符串,那么它有charAt方法,然后最后一个组件将检查字符串是否为空。
我试着用一些SO questions和here和here too !!
有相似(typeof
和instanceof
)其他可用的方法来测试它,所以我决定测试它的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
检查失败?
'如果(string2.charAt)'只检查方法是否定义,空字符串仍然是一个字符串,所以将返回true – charlietfl
@charlietfl plz引用adeneo的答案,他说:“一个简单的字符串不是一个对象,它是一个主要的数据类型,并且没有原型,与用新String创建的String对象相反。“ – stackunderflow
所以空字符串定义为文字不会返回true如果检查charAt函数的存在 – stackunderflow