sta*_*low 5 javascript string instanceof
我正在按照教程建议检查对象是否为字符串而不是空,如下所示:
var s = "text here";
if ( s && s.charAt && s.charAt(0))
Run Code Online (Sandbox Code Playgroud)
据说如果s是字符串,那么它有一个方法charAt然后最后一个组件将检查字符串是否为空.
我尝试用其他可用的方法测试它,比如(typeof和instanceof)使用一些SO问题,这里和这里也是!!
所以我决定在Js Bin中测试它:jsbin代码如下:
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 !!");
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题是:
1-为什么字符串为空时检查字符串失败string2.charAt?
2-为什么instanceof检查失败?
字符串值不是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 -不同类型值的类型.字符串类型,例如,表示字符串值.
1- 为什么使用 string2.charAt 当字符串为空时检查字符串失败?
由于第一个条件失败,以下表达式的计算结果为 false:
var string2 = "";
if (string2 && string2.charAt) { console.log("doesn't output"); }
Run Code Online (Sandbox Code Playgroud)
第二行基本上相当于:
if (false && true) { console.log("doesn't output"); }
Run Code Online (Sandbox Code Playgroud)
例如:
if (string2) { console.log("this doesn't output since string2 == false"); }
if (string2.charAt) { console.log('this outputs'); }
Run Code Online (Sandbox Code Playgroud)
2- 为什么instanceof检查失败?
这会失败,因为在 javascript 中,字符串可以是文字或对象。例如:
var myString = new String("asdf");
myString instanceof String; // true
Run Code Online (Sandbox Code Playgroud)
然而:
var myLiteralString = "asdf";
myLiteralString instanceof String; // false
Run Code Online (Sandbox Code Playgroud)
您可以通过检查类型和:来可靠地判断它是否是字符串instanceof:
str instanceof String || typeof str === "string";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15633 次 |
| 最近记录: |