javascript如何判断类型

ppylox
·6/20/2021·6 阅读
AI 摘要模型根据正文自动生成,仅供参考

JavaScript判断类型常用typeof和Object.prototype.toString.call两种方法。typeof对字符串返回string,布尔返回boolean,对象、数组、null均返回object,函数返回function,未定义变量或undefined返回undefined,但无法区分数组与null。Object.prototype.toString.call可精确识别类型,分别返回[object Number]、[object String]、[object Undefined]、[object Boolean]、[object Object]、[object Array]、[object Function]、[object Null],弥补typeof对数组和null判断的不足。

1、对于字符串类型, typeof 返回的值是 string。比如typeof("123")返回的值是string。 \n

2、对于布尔类型, typeof 返回的值是 boolean 。比如typeof(true)返回的值是boolean。\n

3、对于对象、数组、null 返回的值是 object 。比如typeof(window),typeof(document),typeof(null)返回的值都是object。\n

4、 对于函数类型,返回的值是 function。比如:typeof(eval),typeof(Date)返回的值都是function。\n

5、如果运算数是没有定义的(比如说不存在的变量、函数或者undefined),将返回undefined。比如:typeof(sss)、typeof(undefined)都返回undefined。\n


\n

console.log(Object.prototype.toString.call(123)) //[object Number]\n

console.log(Object.prototype.toString.call('123')) //[object String]\n

console.log(Object.prototype.toString.call(undefined)) //[object Undefined]\n

console.log(Object.prototype.toString.call(true)) //[object Boolean]\n

console.log(Object.prototype.toString.call({})) //[object Object]\n

console.log(Object.prototype.toString.call([])) //[object Array]\n

console.log(Object.prototype.toString.call(function(){})) //[object Function]\n

console.log(Object.prototype.toString.call(null)) //[object Null]

相关文章