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


当前回答

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

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

其他回答

一种简单快速的测试方法是使用构造函数名称属性。

let x = "abc";
console.log(x.constructor.name === "String"); // true

let y = new String('abc');
console.log(y.constructor.name === "String"); // true

表演

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

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

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

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

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

取自lodash:

function isString(val) {
   return typeof val === 'string' || ((!!val && typeof val === 'object') && Object.prototype.toString.call(val) === '[object String]');
}

console.log(isString('hello world!')); // true
console.log(isString(new String('hello world'))); // true

一个简单的解决方案是:

var x = "hello"

if(x === x.toString()){
// it's a string 
}else{
// it isn't
}

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

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