【发布时间】:2011-09-11 07:22:52
【问题描述】:
如何检查 var 是否为 JavaScript 中的字符串?
我试过了,还是不行……
var a_string = "Hello, I'm a string.";
if (a_string typeof 'string') {
// this is a string
}
【问题讨论】:
标签: javascript string variable-types
如何检查 var 是否为 JavaScript 中的字符串?
我试过了,还是不行……
var a_string = "Hello, I'm a string.";
if (a_string typeof 'string') {
// this is a string
}
【问题讨论】:
标签: javascript string variable-types
你很亲密:
if (typeof a_string === 'string') {
// this is a string
}
在相关说明中:如果使用new String('hello') 创建字符串,则上述检查将不起作用,因为类型将改为Object。有一些复杂的解决方案可以解决这个问题,但最好避免以这种方式创建字符串。
【讨论】:
if(typeof(str) === typeof(String()))
typeof 运算符不是中缀(因此您的示例中的 LHS 没有意义)。
你需要这样使用它......
if (typeof a_string == 'string') {
// This is a string.
}
请记住,typeof 是一个运算符,而不是一个函数。尽管如此,您会看到typeof(var) 在野外被大量使用。这和var a = 4 + (1) 一样有意义。
另外,你也可以使用==(相等比较运算符),因为两个操作数都是Strings(typeof总是返回一个String),JavaScript 被定义为执行与我使用===(严格比较运算符)时相同的步骤。
作为Box9 mentions,这个won't detect 是一个实例化的String 对象。
你可以用......来检测它。
var isString = str instanceof String;
...或...
var isString = str.constructor == String;
但是这在多window 环境中不起作用(想想iframes)。
你可以通过...解决这个问题
var isString = Object.prototype.toString.call(str) == '[object String]';
但同样,(如Box9 mentions),您最好只使用文字String 格式,例如var str = 'I am a string';.
【讨论】:
if(myVar.toUpperCase) alert('I am a string');?见:jsfiddle.net/tb3t4nsx
{ toUpperCase: '' }
结合前面的答案提供了这些解决方案:
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;
}
【讨论】:
typeof 没有函数形式,你只是用这些括号控制操作的顺序。有些人可能会发现它在某些情况下更具可读性。
filename 周围的括号仅对单个语句进行分组,因此无用且无关紧要。这个答案的得分为 0 是一件好事,因为它是错误的、误导的和无益的;如果有负分就更好了。
在所有情况下检查 null 或 undefined a_string
if (a_string && typeof a_string === 'string') {
// this is a string and it is not null or undefined.
}
【讨论】:
typeof null 和typeof undefined 永远不会返回'string',所以typeof a_string 就足够了。很抱歉发布了 necropost
我个人的方法似乎适用于所有情况,它是测试是否存在所有仅在字符串中出现的成员。
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/
我想知道这种方法是否存在缺陷,但多年来我一直很好用。
【讨论】: