如何确定变量是字符串还是JavaScript中的其他变量?
当前回答
取自lodash:
function isString(val) {
return typeof val === 'string' || ((!!val && typeof val === 'object') && Object.prototype.toString.call(val) === '[object String]');
}
console.log(isString('hello world!')); // true
console.log(isString(new String('hello world'))); // true
其他回答
我建议使用jQuery或lodash/Undercore中的内置函数。它们更易于使用和阅读。
任何一个函数都将处理上述DRAX的情况。。。也就是说,它们都检查(A)变量是字符串文本还是(B)它是string对象的实例。在这两种情况下,这些函数都将值正确地标识为字符串。
lodash/Undercore.js
if(_.isString(myVar))
//it's a string
else
//it's something else
jQuery
if($.type(myVar) === "string")
//it's a string
else
//it's something else
有关详细信息,请参阅_.isString()的lodash文档。
有关详细信息,请参阅$.type()的jQuery文档。
这是对我有用的:
if (typeof myVar === 'string' || myVar instanceof String)
// it's a string
else
// it's something else
一个简单的解决方案是:
var x = "hello"
if(x === x.toString()){
// it's a string
}else{
// it isn't
}
以下方法将检查任何变量是否为字符串(包括不存在的变量)。
const is_string = value => {
try {
return typeof value() === 'string';
} catch (error) {
return false;
}
};
let example = 'Hello, world!';
console.log(is_string(() => example)); // true
console.log(is_string(() => variable_doesnt_exist)); // false
function isString (obj) {
return (Object.prototype.toString.call(obj) === '[object String]');
}
我在这里看到了:
http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/