JS-数据类型(02)
概述
JavaScript严格来说总有六中属性值:
number
string
boolen
underfined
null
object
。
object
又分为三类:
- 狭义的对象
- Array 数组
- function 函数
在js中,function
是一个数据类型,他可以被赋值给变量,这是非常特殊的一个点。
1 | const addNum = (a,b) => { |
本文会先介绍null
,undefined
,boolen
,其余在后续的小节介绍。
Typeof
判断数据的类型有三种方法:
typeof
instanceof
Object.prototype.toString
typeof会返回的值为number
,string
,boolen
,undefined
,function
null返回的是object
,数组返回的也是object
1 | typeof null // "object" |
null与undefined
和常识不同,一个变量是可以被赋值为undefined
的
1 | let num = undefined; |
null
和undefined
都可以表示没有,语法没有任何区别,在==
中也表现为相等,在if
中都表示false
1 | if (!undefined) { |
但是两者转化的时候不同:
undefined
转化为NaN
null
转化为0
1 | let num = undefined; |
具体理解,undefined
表示未定义,null
表示为当前值为空
1 | // 变量声明了,但没有赋值 |
布尔值
布尔值只有true
和false
两个值
在期望得到布尔值的情况下,会自动将一些值转化为布尔值
以下值都被转化为false
:
undefined
null
false
0
NaN
""
或者''
其他的值都被转化为true
1 | if ([]) { |
评论