如何确定变量是字符串还是JavaScript中的其他变量?
当前回答
if (s && typeof s.valueOf() === "string") {
// s is a string
}
既适用于字符串文本let s=“blah”,也适用于对象字符串let s=新字符串('blah')
其他回答
我还发现这也很好,而且比其他例子要短得多。
if (myVar === myVar + '') {
//its string
} else {
//its something else
}
通过串联空引号,它将值转换为字符串。如果myVar已经是字符串,则If语句成功。
Typechecker助手:
function isFromType(variable, type){
if (typeof type == 'string') res = (typeof variable == type.toLowerCase())
else res = (variable.constructor == type)
return res
}
用法:
isFromType('cs', 'string') //true
isFromType('cs', String) //true
isFromType(['cs'], Array) //true
isFromType(['cs'], 'object') //false
此外,如果您希望它是递归的(像作为对象的数组),可以使用instanceof。
(['cs']对象实例//true)
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
表演
为了扩展@DRAX的答案,我会这样做:
function isWhitespaceEmptyString(str)
{
//RETURN:
// = 'true' if 'str' is empty string, null, undefined, or consists of white-spaces only
return str ? !(/\S/.test(str)) : (str === "" || str === null || str === undefined);
}
它还将考虑null和未定义的类型,并将处理非字符串类型,例如0。