一、typeof的作用
在JavaScript中,变量未经声明就使用,系统是会报错的。但是,typeof却是js中有且仅有的一个特例。
typeof的作用就是用来区分数据类型的,下面先说说typeof的使用方法,以判断n的数据类型为例:
1、typeof n;
2、typeof(n);
这两种方法结果是一样的。
二、typeof返回的数据类型
数据类型包括六大类:其中四种原始数据和两种复杂数据。
原始数据:number、string、boolean、undefined。
复杂数据:object、function。
注意:返回值为字符串,而且全部小写,全部小写,全部小写,重要的事情说三遍。
1、number
console.log(typeof(666));===>number
console.log(typeof(NaN));===>number
console.log(typeof(0)); ===>number
2、string
console.log(typeof('a')); ===>string
console.log(typeof('undefined'));===>string
console.log(typeof('null')); ===>string
3、boolean
console.log(typeof(false));===>boolean
console.log(typeof(true)); ===>boolean
4、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
三、转换成布尔型是false的六个
null、undefined数字0和NaN布尔值中的false- 空字符串
''
console.log(Boolean(null)); ===>false
console.log(Boolean(undefined));===>false
console.log(Boolean(0)); ===>false
console.log(Boolean(NaN)); ===>false
console.log(Boolean(false)); ===>false
console.log(Boolean('')); ===>false
可总结为,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。
251

被折叠的 条评论
为什么被折叠?



