如何检测变量是否为字符串 [英] how to detect if variable is a string
问题描述
如何检测变量是否为字符串?
How can I detect if a variable is a string?
推荐答案
这是ECMAScript规范中指定的方式来确定内部[[Class]]属性。
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
}
[规范]内部属性的值由此规范为每种内置对象定义。主机对象的[[Class]]内部属性的值可以是除Arguments,Array,Boolean,Date,Error,Function之一之外的任何String值, JSON,数学,数字,对象,RegExp,和字符串。内部使用[[Class]]内部属性的值来区分不同类型的对象。请注意,除了通过Object.prototype.toString之外,此规范不提供程序访问该值的任何方法(参见15.2.4.2)。
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]"
如果你使用 typeof
,你得到对象
。
但如果你使用上面的方法,你会得到正确的结果[object String]
。
But if you use the method above, you get the correct result "[object String]"
.
这篇关于如何检测变量是否为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!