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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6286542/
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-08-23 21:06:56  来源:igfitidea点击:

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

javascriptstringvariable-types

提问by vitto

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

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

I've tried this and it doesn't work...

我试过这个,它不起作用......

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

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

回答by David Tang

You were close:

你很接近:

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


On a related note: the above check won't work if a string is created with new String('hello')as the type will be Objectinstead. There are complicated solutions to work around this, but it's better to just avoid creating strings that way, ever.

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

回答by alex

The typeofoperator isn't an infix (so the LHS of your example doesn't make sense).

typeof运营商不中缀(所以你的榜样的LHS没有意义)。

You need to use it like so...

你需要像这样使用它......

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

Remember, typeofis an operator, not a function. Despite this, you will see typeof(var)being used a lot in the wild. This makes as much sense as var a = 4 + (1).

请记住,typeof是运算符,而不是函数。尽管如此,您还是会看到typeof(var)它在野外被大量使用。这与var a = 4 + (1).

Also, you may as well use ==(equality comparison operator) since both operands are Strings (typeofalwaysreturns a String), JavaScript is defined to perform the same steps had I used ===(strict comparison operator).

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

As Box9 mentions, this won't detecta instantiated Stringobject.

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

You can detect for that with....

你可以用...检测到。

var isString = str instanceof String;

jsFiddle.

js小提琴

...or...

...或者...

var isString = str.constructor == String;

jsFiddle.

js小提琴

Butthis won't work in a multi windowenvironment (think iframes).

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

You can get around this with...

你可以通过...

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

jsFiddle.

js小提琴

But again, (as Box9 mentions), you are better off just using the literal Stringformat, e.g. var str = 'I am a string';.

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

Further Reading.

进一步阅读

回答by Alf Eaton

Combining the previous answers provides these solutions:

结合前面的答案提供了这些解决方案:

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

or

或者

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

回答by redisko

Following expression returns true:

以下表达式返回true

'qwe'.constructor === String

Following expression returns true:

以下表达式返回true

typeof 'qwe' === 'string'

Following expression returns false(sic!):

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

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

Following expression returns true:

以下表达式返回true

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

Best and right way (imho):

最好和正确的方式(恕我直言):

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

回答by Master James

Now days I believe it's preferred to use a function form of typeof() so...

现在我相信最好使用 typeof() 的函数形式,所以......

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

回答by Kurkula

check for null or undefined in all cases a_string

在所有情况下检查 null 或 undefined a_string

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

回答by ingredient_15939

My personal approach, which seems to work for all cases, is testing for the presence of members that will all only be present for strings.

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

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

See: http://jsfiddle.net/x75uy0o6/

见:http: //jsfiddle.net/x75uy0o6/

I'd like to know if this method has flaws, but it has served me well for years.

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