如何确定变量是字符串还是JavaScript中的其他变量?


当前回答

这是对我有用的:

if (typeof myVar === 'string' || myVar instanceof String)
// it's a string
else
// it's something else

其他回答

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)

以下方法将检查任何变量是否为字符串(包括不存在的变量)。

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 isNumber(item) {
    return (parseInt(item) + '') === item;
}

例如:

isNumber(123);   //true
isNumber('123'); //true
isNumber('123a');//false
isNumber('');    //false
if (s && typeof s.valueOf() === "string") {
  // s is a string
}

既适用于字符串文本let s=“blah”,也适用于对象字符串let s=新字符串('blah')

为了扩展@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。