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


当前回答

老实说,我不明白为什么在这种情况下不简单地使用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'));

其他回答

var a = new String('')
var b = ''
var c = []

function isString(x) {
  return x !== null && x !== undefined && x.constructor === String
}

console.log(isString(a))
console.log(isString(b))
console.log(isString(c))

您可以使用此函数确定任何对象的类型:

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

我不确定你的意思是知道它是一个类型字符串而不管它的内容,还是它的内容是一个数字或字符串而不管其类型。所以要知道它的类型是否是字符串,这已经得到了答案。但要根据它的内容知道它是字符串还是数字,我会使用这个:

function isNumber(item) {
    return (parseInt(item) + '') === item;
}

例如:

isNumber(123);   //true
isNumber('123'); //true
isNumber('123a');//false
isNumber('');    //false

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

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

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