我如何检查如果一个变量是JavaScript字符串?

我如何检查如果一个变量是JavaScript字符串?

我试过了,不管用……

var a_string = "Hello, I'm a string.";


if (a_string typeof 'string') {
// this is a string
}
240908 次浏览

你很接近:

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)一样有意义。

同样,你也可以使用==(相等比较操作符),因为两个操作数都是String (typeof 总是返回一个String), JavaScript被定义为执行与我使用===(严格比较操作符)相同的步骤。

作为Box9提到,这个不检测是一个实例化的String对象。

您可以使用....进行检测

var isString = str instanceof String;

jsFiddle

…或…

var isString = str.constructor == String;

jsFiddle

在多window环境中不起作用(想想iframes)。

你可以用…

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]'

我个人的方法(似乎适用于所有情况)是测试只会出现在字符串中的成员是否存在。

function isString(x) {
return (typeof x == 'string' || typeof x == 'object' && x.toUpperCase && x.substr && x.charAt && x.trim && x.replace ? true : false);
}

看:http://jsfiddle.net/x75uy0o6/

我想知道这种方法是否有缺陷,但它多年来一直很有效。

现在我认为最好使用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.
}

下面的表达式返回真正的:

'qwe'.constructor === String

下面的表达式返回真正的:

typeof 'qwe' === 'string'

下面的表达式返回 (sic!):

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

下面的表达式返回真正的:

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

最佳和正确的方法(恕我直言):

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