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


当前回答

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

其他回答

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

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

例如:

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

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

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

由于有580+人投票给了一个错误的答案,而有800+人投票支持一个有效但猎枪式的答案,我认为应该用一种大家都能理解的更简单的形式来重复我的答案。

function isString(x) {
  return Object.prototype.toString.call(x) === "[object String]"
}

或者,内联(我有一个UltiSnip设置):

Object.prototype.toString.call(myVar) === "[object String]"

仅供参考,巴勃罗·圣克鲁斯的答案是错误的,因为新字符串(“String”)的类型是对象

DRAX的答案准确且实用,应该是正确的答案(因为巴勃罗·圣克鲁斯(Pablo Santa Cruz)绝对是错误的,我不会反对全民投票。)

然而,这个答案也绝对正确,实际上是最好的答案(除了使用lodash/下划线的建议)。免责声明:我为lodash 4代码库做了贡献。

我最初的答案(很明显,很多人都是这么想的)如下:

我从underscore.js代码转换了这个:

['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'].forEach( 
    function(name) { 
        window['is' + name] = function(obj) {
              return toString.call(obj) == '[object ' + name + ']';
    }; 
});

这将定义isString、isNumber等。


在Node.js中,这可以作为一个模块实现:

module.exports = [
  'Arguments',
  'Function', 
  'String', 
  'Number', 
  'Date', 
  'RegExp'
].reduce( (obj, name) => {
  obj[ 'is' + name ] = x => toString.call(x) == '[object ' + name + ']';
  return obj;
}, {});

[编辑]:Object.protype.toString.call(x)也可以在函数和异步函数之间进行描述:

const fn1=()=>new Promise((resolve,reject)=>setTimeout(()=>resolve({}),1000))常量fn2=async()=>({})console.log('fn1',Object.pr原型.toString.call(fn1))console.log('fn2',Object.pr原型.toString.call(fn2))

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

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 isString (obj) {
  return (Object.prototype.toString.call(obj) === '[object String]');
}

我在这里看到了:

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