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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24844039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:26:42  来源:igfitidea点击:

check if an object is string in Javascript

javascriptstringinstanceof

提问by stackunderflow

I was following a tutorial that suggested to check if an object is string and not empty as the following:

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

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

it is said that if s is string then it has a method charAt and then the last component will check if the string is empty or not.

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

I tried to test it with the other available methods like ( typeofand instanceof) using some of the SO questions and here and here too !!

我尝试使用其他可用方法(例如(typeofinstanceof))使用一些SO 问题以及此处此处对其进行测试!

so I decided to test it in Js Bin : jsbin code hereas follow:

所以我决定在 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 !!");
}

Now my questions are :

现在我的问题是:

1- why does the check for string fails when the string is empty using the string2.charAt???

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

2- why does the instanceofcheck failed??

2-为什么instanceof检查失败?

回答by user2864740

string valuesare not String objects(which is why the instanceof fails)2.

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

To cover both cases using "type-checking" it would be typeof x === "string" || x instanceof String; the first only matches stringsand the latter matches Strings.

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

The tutorial assumes that [only] String objects - or string values which are promoted1- have a charAtmethod and so uses "duck-typing". If the method does exist, then it is called. If charAtis used out-of-bounds then an empty string "", which is a false-y value, is returned.

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

The tutorial code would also accept a string of "\0", while s && s.lengthwould not - but it would also "work" on arrays (or jQuery objects, etc). Personally, I trustthe caller to provide the allowed values/types and use as little "type-checking" or special-casing as possible.

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



1For primitive values of string, number, and boolean there is a corresponding object type of String, Number, and Boolean, respectively. When x.propertyis used on one of these primitive values the effect is ToObject(x).property- hence the "promotion". This is discussed in ES5: 9.9 - ToObject.

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

Neither the null or undefined values have corresponding objects (or methods). Functions are already objects but have a historically different, and useful, typeofresult.

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

2See ES5: 8 - Typesfor the different types of values. The String Type, eg., represents a stringvalue.

2请参阅ES5:8 -不同类型值的类型。字符串类型,例如,代表一个字符串值。

回答by David Sherret

1- Why does the check for string fails when the string is empty using the string2.charAt?

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

The following expression evaluates to false because the first condition fails:

以下表达式的计算结果为 false,因为第一个条件失败:

var string2 = "";
if (string2 && string2.charAt) { console.log("doesn't output"); }

That second line is basically equivalent to:

第二行基本上相当于:

if (false && true) { console.log("doesn't output"); }

So for example:

例如:

if (string2) { console.log("this doesn't output since string2 == false"); }
if (string2.charAt) { console.log('this outputs'); }

2- Why does the instanceof check fail?

2- 为什么 instanceof 检查失败?

This fails because, in javascript, string can be literals or objects. For example:

这失败了,因为在 javascript 中,字符串可以是文字或对象。例如:

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

However:

然而:

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

You can reliably tell if it's a string by checking both the type and the instanceof:

您可以通过检查类型和 来可靠地判断它是否是字符串instanceof

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