如何确定变量是字符串还是JavaScript中的其他变量?
当前回答
一个简单的解决方案是:
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/
一种简单快速的测试方法是使用构造函数名称属性。
let x = "abc";
console.log(x.constructor.name === "String"); // true
let y = new String('abc');
console.log(y.constructor.name === "String"); // true
表演
isString()使用可选链接和最新标准检查传递的参数是否为字符串:
const isString = (value) => {
return value?.constructor === String;
}
我建议使用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文档。