我怎样才能检查一个var是JavaScript中的string?
我怎样才能检查一个var是JavaScript中的string?
我试过这个,它不工作…
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 } 
 在相关说明上:如果一个string是用new String('hello')创build的,则上述检查将不起作用,因为types将是Object 。 解决这个问题有复杂的解决scheme,但是最好避免以这种方式创buildstring。 
  typeof运算符不是中缀(所以你的例子的LHS没有意义)。 
你需要像这样使用它…
 if (typeof a_string == 'string') { // This is a string. } 
 请记住, typeof是一个操作符,而不是一个函数。 尽pipe如此,你会看到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环境中工作(想想iframe )。 
你可以解决这个…
 var isString = Object.prototype.toString.call(str) == '[object String]'; 
jsFiddle 。
 但是,再次(如Box9提到的 ),最好使用String格式,例如var str = 'I am a string';  。 
进一步阅读 。
结合以前的答案提供了这些解决scheme:
 if (typeof str == 'string' || str instanceof String) 
要么
 Object.prototype.toString.call(str) == '[object String]' 
现在,我相信最好使用typeof()的函数forms,所以…
 if(filename === undefined || typeof(filename) !== "string" || filename === "") { console.log("no filename aborted."); return; } 
在所有情况下检查空或未定义a_string
 if (a_string && typeof a_string === 'string') { // this is a string and it is not null or undefined. } 
我个人的方法,似乎适用于所有情况,正在testing只存在于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/
我想知道这个方法是否存在缺陷,但是这个方法对我来说已经好几年了。