如何确定变量是字符串还是JavaScript中的其他变量?
当前回答
我发现这种简单的技术对字符串的类型检查很有用-
String(x) === x // true, if x is a string
// false in every other case
常量测试=x=>控制台断言(字符串(x)==x,`不是字符串:${x}`)测试(“某些字符串”)测试(123)//断言失败测试(0)//断言失败测试(/some regex/)//断言失败测试([5],6])//断言失败测试({a:1})//断言失败测试(x=>x+1)//断言失败
同样的技术也适用于Number-
Number(x) === x // true, if x is a number
// false in every other case
常量测试=x=>控制台断言(数量(x)==x,`不是数字:${x}`)test(“some string”)//断言失败测试(123)测试(0)测试(/some regex/)//断言失败测试([5],6])//断言失败测试({a:1})//断言失败测试(x=>x+1)//断言失败
对于RegExp-
RegExp(x) === x // true, if x is a regexp
// false in every other case
常量测试=x=>控制台断言(RegExp(x)==x,`不是正则表达式:${x}`)test(“some string”)//断言失败测试(123)//断言失败测试(0)//断言失败测试(/some regex/)测试([5],6])//断言失败测试({a:1})//断言失败测试(x=>x+1)//断言失败
与对象相同-
Object(x) === x // true, if x is an object
// false in every other case
NB、正则表达式、数组和函数也被视为对象。
常量测试=x=>控制台断言(对象(x)==x,`不是对象:${x}`)test(“some string”)//断言失败测试(123)//断言失败测试(0)//断言失败测试(/some regex/)测试([5,6])测试({a:1})测试(x=>x+1)
但是,检查Array有点不同-
Array.isArray(x) === x // true, if x is an array
// false in every other case
常量测试=x=>控制台断言(Array.isArray(x),`不是数组:${x}`)test(“some string”)//断言失败测试(123)//断言失败测试(0)//断言失败测试(/some regex/)//断言失败测试([5,6])测试({a:1})//断言失败测试(x=>x+1)//断言失败
但是,此技术不适用于函数-
Function(x) === x // always false
对于@Faither-
const fmt=JSON.stringify函数测试1(){常量a=“1”常量b=1console.log(`编号(${fmt(a)})==${mt(b)}`,编号(a)==b)//true}函数测试2(){常量a=“1”常量b=1console.log(`Number.isInteger(${fmt(a)})`,Number.isInteger(a))//falseconsole.log(`Number.isInteger(${fmt(b)})`,Number.isInteger(b))//true}函数测试3(){name=1//全局名称将始终为字符串console.log(fmt(名称))//“1”console.log(`字符串(${fmt(名称)})==${mt(名称)}`,字符串(名称)==名称)//true}函数测试4(){常量名称=1//本地名称console.log(fmt(名称))//1console.log(`字符串(${fmt(名称)})==${mt(名称)}`,字符串(名称)==名称)//false}测试1();test2();测试3();测试4()
其他回答
我喜欢使用这个简单的解决方案:
var myString = "test";
if(myString.constructor === String)
{
//It's a string
}
为了扩展@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。
这是对我有用的:
if (typeof myVar === 'string' || myVar instanceof String)
// it's a string
else
// it's something else
这是一个很好的例子,说明了为什么性能很重要:
如果做得不正确,对字符串进行测试这样简单的操作可能会很昂贵。
例如,如果我想写一个函数来测试某个东西是否是字符串,我可以用以下两种方法之一:
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
我不确定你的意思是知道它是一个类型字符串而不管它的内容,还是它的内容是一个数字或字符串而不管其类型。所以要知道它的类型是否是字符串,这已经得到了答案。但要根据它的内容知道它是字符串还是数字,我会使用这个:
function isNumber(item) {
return (parseInt(item) + '') === item;
}
例如:
isNumber(123); //true
isNumber('123'); //true
isNumber('123a');//false
isNumber(''); //false