如何确定变量是字符串还是JavaScript中的其他变量?
当前回答
您可以使用此函数确定任何对象的类型:
var type = function(obj) {
return Object.prototype.toString.apply(obj).replace(/\[object (.+)\]/i, '$1').toLowerCase();
};
要检查变量是否为字符串,请执行以下操作:
type('my string') === 'string' //true
type(new String('my string')) === 'string' //true
type(`my string`) === 'string' //true
type(12345) === 'string' //false
type({}) === 'string' // false
https://codepen.io/patodiblasi/pen/NQXPwY?editors=0012
要检查其他类型:
type(null) //null
type(undefined) //undefined
type([]) //array
type({}) //object
type(function() {}) //function
type(123) //number
type(new Number(123)) //number
type(/some_regex/) //regexp
type(Symbol("foo")) //symbol
其他回答
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)
您可以使用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建议弃用基本对象包装器。
我建议使用jQuery或lodash/Undercore中的内置函数。它们更易于使用和阅读。
任何一个函数都将处理上述DRAX的情况。。。也就是说,它们都检查(A)变量是字符串文本还是(B)它是string对象的实例。在这两种情况下,这些函数都将值正确地标识为字符串。
lodash/Undercore.js
if(_.isString(myVar))
//it's a string
else
//it's something else
jQuery
if($.type(myVar) === "string")
//it's a string
else
//it's something else
有关详细信息,请参阅_.isString()的lodash文档。
有关详细信息,请参阅$.type()的jQuery文档。
我发现这种简单的技术对字符串的类型检查很有用-
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 type = function(obj) {
return Object.prototype.toString.apply(obj).replace(/\[object (.+)\]/i, '$1').toLowerCase();
};
要检查变量是否为字符串,请执行以下操作:
type('my string') === 'string' //true
type(new String('my string')) === 'string' //true
type(`my string`) === 'string' //true
type(12345) === 'string' //false
type({}) === 'string' // false
https://codepen.io/patodiblasi/pen/NQXPwY?editors=0012
要检查其他类型:
type(null) //null
type(undefined) //undefined
type([]) //array
type({}) //object
type(function() {}) //function
type(123) //number
type(new Number(123)) //number
type(/some_regex/) //regexp
type(Symbol("foo")) //symbol
推荐文章
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 将整数转换为字符串,以逗号表示千
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- printf()和puts()在C语言中的区别是什么?
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔
- TypeScript枚举对象数组
- 在React.js中正确的img路径
- 在React.js中更新组件onScroll的样式
- onClick ReactJS调用多个函数