gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 05:49:57 25 4
gpt4 key购买 nike

我正在学习一个教程,该教程建议检查一个对象是否为字符串而不是空的,如下所示:

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

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

我尝试使用其他可用方法(typeofinstanceof)使用一些 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 检查失败??

最佳答案

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

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

本教程假定 [仅] 字符串对象 - 或被提升1 的字符串值 - 具有 charAt 方法,因此使用 "duck-typing" .如果该方法确实存在,则调用它。如果 charAt 被越界使用,则返回一个空字符串 "",这是一个 false-y 值。

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


1 对于字符串、数字和 bool 值的原始值,分别有一个对应的对象类型字符串、数字和 bool 值。当 x.property 用于这些原始值之一时,效果是 ToObject(x).property - 因此是“提升”。这在 ES5: 9.9 - ToObject 中讨论.

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

2 参见 ES5: 8 - Types对于不同类型的值。例如,字符串类型表示一个字符串 值。

关于javascript - 检查对象是否为 Javascript 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24844039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com