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


当前回答

isString()使用可选链接和最新标准检查传递的参数是否为字符串:

const isString = (value) => { 
    return value?.constructor === String;
}

其他回答

只有字符串而没有数字的代码

isNaN("A") = true;
parseInt("A") = NaN;
isNaN(NaN) = true;

然后我们可以使用isNaN(parseInt())来只包含字符串

let ignoreNumbers=“ad123a4m”;让ign=ignoreNumbers.split(“”).map((ele)=>isNaN(parseInt(ele))?ele:“”).加入(“”);console.log(ign);

取自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
if (s && typeof s.valueOf() === "string") {
  // s is a string
}

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

您可以使用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建议弃用基本对象包装器。

这是对我有用的:

if (typeof myVar === 'string' || myVar instanceof String)
// it's a string
else
// it's something else