如何检查 var 是否是 JavaScript 中的字符串?
我试过这个,它不起作用......
var a_string = "Hello, I'm a string.";
if (a_string typeof 'string') {
// this is a string
}
如何检查 var 是否是 JavaScript 中的字符串?
我试过这个,它不起作用......
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)
.
此外,您也可以使用==
(相等比较运算符),因为两个操作数都是String
s(typeof
总是返回 a String
),JavaScript 被定义为执行与我使用相同的步骤===
(严格比较运算符)。
正如Box9 提到的,这不会检测到实例化的String
对象。
你可以用......检测到。
var isString = str instanceof String;
...或者...
var isString = str.constructor == String;
但这在多环境中不起作用window
(想想iframe
)。
你可以解决这个问题...
var isString = Object.prototype.toString.call(str) == '[object String]';
但同样,(正如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'
最好和正确的方法(恕我直言):
if (someVariable.constructor === String) {
...
}
现在,我相信最好使用 typeof() 的函数形式,所以......
if(filename === undefined || typeof(filename) !== "string" || filename === "") {
console.log("no filename aborted.");
return;
}
在所有情况下检查 null 或 undefined a_string
if (a_string && typeof a_string === 'string') {
// this is a string and it is not null or undefined.
}
我个人的方法似乎适用于所有情况,它是测试是否存在所有仅存在于字符串的成员。
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/
我想知道这种方法是否存在缺陷,但多年来它一直对我有用。