如何确定变量是字符串还是JavaScript中的其他变量?
当前回答
以下方法将检查任何变量是否为字符串(包括不存在的变量)。
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
其他回答
以下方法将检查任何变量是否为字符串(包括不存在的变量)。
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
编辑:当前的方法是typeof value==“string”。例如:
const str = 'hello';
if (typeof str === 'string') { ... }
自节点v4以来,以下内容已被弃用。
如果您在node.js环境中工作,那么只需在utils中使用内置函数isString即可。
const util = require('util');
if (util.isString(myVar)) {}
这对我来说已经足够好了。
警告:这不是一个完美的解决方案。请看我帖子的底部。
Object.prototype.isString = function() { return false; };
String.prototype.isString = function() { return true; };
var isString = function(a) {
return (a !== null) && (a !== undefined) && a.isString();
};
你可以像下面这样使用。
//return false
isString(null);
isString(void 0);
isString(-123);
isString(0);
isString(true);
isString(false);
isString([]);
isString({});
isString(function() {});
isString(0/0);
//return true
isString("");
isString(new String("ABC"));
警告:在以下情况下,此操作不正确:
//this is not a string
var obj = {
//but returns true lol
isString: function(){ return true; }
}
isString(obj) //should be false, but true
您可以使用此函数确定任何对象的类型:
var type = function(obj) {
return Object.prototype.toString.apply(obj).replace(/\[object (.+)\]/i, '$1').toLowerCase();
};
要检查变量是否为字符串,请执行以下操作:
type('my string') === 'string' //true
type(new String('my string')) === 'string' //true
type(`my string`) === 'string' //true
type(12345) === 'string' //false
type({}) === 'string' // false
https://codepen.io/patodiblasi/pen/NQXPwY?editors=0012
要检查其他类型:
type(null) //null
type(undefined) //undefined
type([]) //array
type({}) //object
type(function() {}) //function
type(123) //number
type(new Number(123)) //number
type(/some_regex/) //regexp
type(Symbol("foo")) //symbol
老实说,我不明白为什么在这种情况下不简单地使用typeof:
if (typeof str === 'string') {
return 42;
}
是的,它会对对象包装的字符串(例如,新字符串('o'))失败,但这些被广泛认为是一种糟糕的做法,大多数现代开发工具可能会阻止它们的使用。(如果您看到一个,请修复它!)
Object.prototype.toString技巧是所有前端开发人员在其职业生涯中的某一天都会犯下的错误,但不要让它通过巧妙的打磨来欺骗你:只要有人修补Object原型,它就会崩溃:
constisString=thing=>Object.protype.toString.call(thing)=='[objectString]';console.log(isString('fo'));Object.prototype.toString=()=>42;console.log(isString('fo'));