【发布时间】:2014-09-10 17:10:07
【问题描述】:
我正在关注一个建议检查对象是否为字符串且不为空的教程,如下所示:
var s = "text here";
if ( s && s.charAt && s.charAt(0))
据说如果s是字符串,那么它有一个charAt方法,然后最后一个组件会检查字符串是否为空。
我尝试使用其他可用方法来测试它,例如(typeof 和 instanceof)使用一些 SO questions 和 here 和 here too !!
所以我决定在 Js Bin 中测试它: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-为什么使用string2.charAt字符串为空时检查字符串失败???
2- 为什么instanceof 检查失败??
【问题讨论】:
-
if(string2.charAt)只检查是否定义了方法,空字符串仍然是字符串,因此将返回 true -
@charlietfl 请参考 adeneo 的回答,他说“简单的字符串不是对象,它是主要数据类型,并且没有原型,而不是使用新字符串创建的字符串对象。 "
-
因此,如果检查 charAt 函数是否存在,定义为文字的空字符串将不会返回 true
-
@stackunderflow 如果使用提供的代码,它会。 (因为
"".charAt(0) -> "" -> false-y。不起作用的东西是"" instanceof String && ..,因为它是一个string值,而不是一个String对象。 -
@stackunderflow 按照你的逻辑你永远做不到
'somestring'.charAt(n)
标签: javascript string instanceof