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


当前回答

if (s && typeof s.valueOf() === "string") {
  // s is a string
}

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

其他回答

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

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

例如:

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

isString()使用可选链接和最新标准检查传递的参数是否为字符串:

const isString = (value) => { 
    return value?.constructor === String;
}

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

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

我还发现这也很好,而且比其他例子要短得多。

if (myVar === myVar + '') {
   //its string
} else {
   //its something else
}

通过串联空引号,它将值转换为字符串。如果myVar已经是字符串,则If语句成功。

function isString (obj) {
  return (Object.prototype.toString.call(obj) === '[object String]');
}

我在这里看到了:

http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/