在JavaScript中,变量未经声明就使用,系统是会报错的。但是,typeof却是js中有且仅有的一个特例。
typeof的作用就是用来区分数据类型的,下面先说说typeof的使用方法,以判断n的数据类型为例:
1、typeof n;
2、typeof(n);
这两种方法结果是一样的。
数据类型包括六大类:其中四种原始数据和两种复杂数据。
原始数据:number、string、boolean、undefined。
复杂数据:object、function。
1、number
console.log(typeof(666));===>number console.log(typeof(NaN));===>number console.log(typeof(0)); ===>number2、string
console.log(typeof('a')); ===>string console.log(typeof('undefined'));===>string console.log(typeof('null')); ===>string3、boolean
console.log(typeof(false));===>boolean console.log(typeof(true)); ===>boolean4、undefined
两种情况:
变量未经声明 console.log(typeof(a));===>undefined
变量的值就是undefined console.log(typeof(undefined));===>undefined
5、object
var a = {};//对象 console.log(typeof(a)); ===> object var b = [];//数组 console.log(typeof(b)); ===> object console.log(typeof(null)); ===> object //特殊的6、function
var a = function(){}; console.log(typeof(a));===>function可总结为,js中五中基本数据类型undefined、null、布尔型、数字和字符串,外加对象共六中类型中,只有undefined、null、布尔值中的false、数字中的0和NaN,和字符串中的空字符串'',共计6种值被转换成false, 其余的都被转换成true。
console.log(typeof(null)); ===>object console.log(typeof(undefined)); ===>undefined console.log(typeof(0)); ===>number console.log(typeof(NaN)); ===>number console.log(typeof(false)); ===>boolean console.log(typeof('')); ===>string注意:
1. console.log(typeof(a)); ===> undefined 2. console.log(typeof(undefined)); ===> undefined 3. console.log(typeof(typeof(a))); ===> string这是因为1中的typeof(a)返回的undefined是字符串类型,所以3就相当于typeof('undefined'),结果为string。
参考:
1、JavaScript布尔类型及转换------ https://segmentfault.com/a/1190000007274034
2、关于JavaScript中typeof的用法------https://blog.csdn.net/inthuixiang/article/details/78586368
3、https://www.runoob.com/js/js-typeof.html
4、http://www.w3school.com.cn/js/js_datatypes.asp
如果您喜欢编程,或者您需要网站开发、app、小程序等等。。可以加入我们qq群:333530575。
