如何检查var是否是JavaScript中的字符串?
如何检查var是否是JavaScript中的字符串?如何检查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
总是返回String
),JavaScript是定义为执行相同的步骤了我以前===
(严格的比较操作符) 。
作为Box9 mentions,这个won't detect实例化的String
对象。
可以检测是否有....
var isString = str instanceof String;
......或者......
var isString = str.constructor == String;
但这不会在多window
环境中工作(认为iframe
S)。
你可以绕过这与...
var isString = Object.prototype.toString.call(str) == '[object String]';
jsFiddle。但是,再次(如Box9 mentions),使用字面String
格式(例如, var str = 'I am a string';
。
哈哈太近了!不幸的是,我今天没有投票。 – 2011-06-08 23:44:54
@ Box9无后顾之忧,无论如何,我的代言人都是封顶的:P – alex 2011-06-08 23:45:16
+1更清晰的答案。 – 2011-06-08 23:45:16
结合以前的答案提供这些解决方案:
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/
我想知道,如果这种方法有缺陷,但它使我受益匪浅多年。
这很容易被任何具有这些方法的旧对象愚弄。 – alex 2015-07-01 01:50:52
这叫做鸭子打字 - 例如如果它像一个字符串一样走路并且它像一个字符串一样对话,那么它可能就是一个字符串。如果你认为这是测试字符串的最好方法,那么你有点疯狂,但是Javascript是一个Thunderdome,你是你。 – 2016-10-19 21:35:32
现在日子里,我相信这是最好使用的typeof的函数形式()等等......
if(filename === undefined || typeof(filename) !== "string" || filename === "") {
console.log("no filename aborted.");
return;
}
没有'typeof'的函数形式,你只是用这些圆括号来控制操作顺序。在某些情况下,有些人可能会发现它更具可读性。 – 2016-10-19 21:33:47
检查null或undefined在所有情况下对a_string
if (a_string && typeof a_string === 'string') {
// this is a string and it is not null or undefined.
}
[检查的
可能重复是否变量是数字或字符串在JavaScript中](http://stackoverflow.com/questions/1303646/check-whether-variable-is-number-or-string-in-javascript) – Flimzy 2015-08-21 20:12:42