如何检查var是否是JavaScript中的字符串

How can I check if a var is a string in JavaScript?

本文关键字:JavaScript 是否是 字符串 var 何检查 检查      更新时间:2023-09-26

如何在JavaScript中检查var是否为字符串?

我试过了,但没用。。。

var a_string = "Hello, I'm a string.";
if (a_string typeof 'string') {
    // this is a string
}

你很接近:

if (typeof a_string === 'string') {
    // this is a string
}

请注意:如果使用new String('hello')创建字符串,则上述检查将不起作用,因为类型将改为Object。有复杂的解决方案可以解决这个问题,但最好永远避免以这种方式创建字符串。

typeof运算符不是中缀(因此示例中的LHS没有意义)。

你需要像这样使用它…

if (typeof a_string == 'string') {
    // This is a string.
}

请记住,typeof是一个运算符,而不是一个函数。尽管如此,你还是会看到typeof(var)在野外被大量使用。这和var a = 4 + (1)一样有意义。

此外,您还可以使用==(相等比较运算符),因为两个操作数都是Strings(typeof总是返回String),所以JavaScript被定义为执行与我使用===(严格比较运算符)相同的步骤。

正如Box9提到的,这不会检测到实例化的String对象。

你可以用…来检测。。。。

var isString = str instanceof String;

jsFiddle。

var isString = str.constructor == String;

jsFiddle。

但是这在多window环境中不起作用(想想iframe s)。

你可以通过。。。

var isString = Object.prototype.toString.call(str) == '[object String]';

jsFiddle。

但是,(正如Box9所提到的),您最好只使用字面String格式,例如var str = 'I am a string';

进一步阅读。

结合前面的答案可以提供以下解决方案:

if (typeof str == 'string' || str instanceof String)

Object.prototype.toString.call(str) == '[object String]'

以下表达式返回true

'qwe'.constructor === String

以下表达式返回true

typeof 'qwe' === 'string'

以下表达式返回false(原文如此!):

typeof new String('qwe') === 'string'

以下表达式返回true

typeof new String('qwe').valueOf() === 'string'

最佳和正确的方式(imho):

if (someVariable.constructor === String) {
   ...
}

现在我认为最好使用typeof()的函数形式,所以…

if(filename === undefined || typeof(filename) !== "string" || filename === "") {
   console.log("no filename aborted.");
   return;
}

在所有情况下检查是否为null或未定义a_string

if (a_string && typeof a_string === 'string') {
    // this is a string and it is not null or undefined.
}