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


当前回答

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

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

其他回答

编辑:当前的方法是typeof value==“string”。例如:

const str = 'hello';
if (typeof str === 'string') { ... }

自节点v4以来,以下内容已被弃用。

如果您在node.js环境中工作,那么只需在utils中使用内置函数isString即可。

const util = require('util');
if (util.isString(myVar)) {}

由于有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))

您可以使用typeof运算符:

var booleanValue = true; 
var numericalValue = 354;
var stringValue = "This is a String";
var stringObject = new String( "This is a String Object" );
alert(typeof booleanValue) // displays "boolean"
alert(typeof numericalValue) // displays "number"
alert(typeof stringValue) // displays "string"
alert(typeof stringObject) // displays "object"

此网页中的示例。(尽管对示例进行了轻微修改)。

在使用new String()创建字符串的情况下,这不会像预期的那样工作,但这很少被使用,并且建议对[1][2]使用。如果您愿意,请查看其他答案以了解如何处理这些问题。


谷歌JavaScript风格指南说,永远不要使用原始对象包装器。Douglas Crockford建议弃用基本对象包装器。

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

我在这里看到了:

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

我建议使用jQuery或lodash/Undercore中的内置函数。它们更易于使用和阅读。

任何一个函数都将处理上述DRAX的情况。。。也就是说,它们都检查(A)变量是字符串文本还是(B)它是string对象的实例。在这两种情况下,这些函数都将值正确地标识为字符串。

lodash/Undercore.js

if(_.isString(myVar))
   //it's a string
else
   //it's something else

jQuery

if($.type(myVar) === "string")
   //it's a string
else
   //it's something else

有关详细信息,请参阅_.isString()的lodash文档。

有关详细信息,请参阅$.type()的jQuery文档。