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


当前回答

var a = new String('')
var b = ''
var c = []

function isString(x) {
  return x !== null && x !== undefined && x.constructor === String
}

console.log(isString(a))
console.log(isString(b))
console.log(isString(c))

其他回答

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

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

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

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

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

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

老实说,我不明白为什么在这种情况下不简单地使用typeof:

if (typeof str === 'string') {
  return 42;
}

是的,它会对对象包装的字符串(例如,新字符串('o'))失败,但这些被广泛认为是一种糟糕的做法,大多数现代开发工具可能会阻止它们的使用。(如果您看到一个,请修复它!)

Object.prototype.toString技巧是所有前端开发人员在其职业生涯中的某一天都会犯下的错误,但不要让它通过巧妙的打磨来欺骗你:只要有人修补Object原型,它就会崩溃:

constisString=thing=>Object.protype.toString.call(thing)=='[objectString]';console.log(isString('fo'));Object.prototype.toString=()=>42;console.log(isString('fo'));

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

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

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

表演