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


当前回答

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

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

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

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

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

其他回答

这对我来说已经足够好了。

警告:这不是一个完美的解决方案。请看我帖子的底部。

Object.prototype.isString = function() { return false; };
String.prototype.isString = function() { return true; };

var isString = function(a) {
  return (a !== null) && (a !== undefined) && a.isString();
};

你可以像下面这样使用。

//return false
isString(null);
isString(void 0);
isString(-123);
isString(0);
isString(true);
isString(false);
isString([]);
isString({});
isString(function() {});
isString(0/0);

//return true
isString("");
isString(new String("ABC"));

警告:在以下情况下,此操作不正确:

//this is not a string
var obj = {
    //but returns true lol
    isString: function(){ return true; }
}

isString(obj) //should be false, but true

这是一个很好的例子,说明了为什么性能很重要:

如果做得不正确,对字符串进行测试这样简单的操作可能会很昂贵。

例如,如果我想写一个函数来测试某个东西是否是字符串,我可以用以下两种方法之一:

1) const isString=str=>(Object.pr原型.toString.call(str)=='[Object String]');

2) const isString=str=>((typeof str=='string')||(str instanceof string));

这两个都非常直接,那么什么可能会影响性能呢?一般来说,函数调用可能会很昂贵,特别是如果您不知道内部发生了什么。在第一个示例中,有一个对Object的toString方法的函数调用。在第二个示例中,没有函数调用,因为typeof和instanceof是运算符。运算符比函数调用快得多。

测试性能时,示例1比示例2慢79%!

参见测试:https://jsperf.com/isstringtype

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

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

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

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

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)