how to detect if variable is a string

如何检测变量是否是字符串?


This is the way specified in the ECMAScript spec to determine the internal [[Class]] property.

if( Object.prototype.toString.call(myvar) == '[object String]' ) {
   // a string
}

From 8.6.2 Object Internal Properties and Methods :

The value of the [[Class]] internal property is defined by this specification for every kind of built-in object. The value of the [[Class]] internal property of a host object may be any String value except one of "Arguments", "Array", "Boolean", "Date", "Error", "Function", "JSON", "Math", "Number", "Object", "RegExp", and "String" . The value of a [[Class]] internal property is used internally to distinguish different kinds of objects. Note that this specification does not provide any means for a program to access that value except through Object.prototype.toString (see 15.2.4.2).


For an example of how this is useful, consider this example:

var str = new String('some string');

alert( typeof str ); // "object"

alert( Object.prototype.toString.call(str) ); // "[object String]"

If you use typeof , you get "object" .

But if you use the method above, you get the correct result "[object String]" .


你可以使用typeof来做到这一点,但对于很多事情来说,这是糟糕的设计。

if (typeof myVar == "string") {
    alert("I'm a string!");
}

使用typeof。

if (typeof foo == 'string')
链接地址: http://www.djcxy.com/p/94974.html

上一篇: 检查一个对象是否是Javascript中的字符串

下一篇: 如何检测变量是否是一个字符串