数据类型
数值(number)
字符串(string)
布尔值(boolean)
undefined
: 表示“未定义”或不存在,即由于目前没有定义,所以此处暂时没有任何值。null
: 表示空值,即此处的值为空。对象(object): 各种值组成的集合。
Symbol
:ES6
新增,表示独一无二的值。
typeof运算符
typeof
运算符可以返回一个值的数据类型。
其中空数组[]
也返回object
类型,这表示在JavaScript
内部,数组本质上只是一种特殊的对象。
当然想要区分数组还是对象,可以使用instanceof
运算符
null
的数据类型也是object
, 由于历史原因造成,为了兼容以前的代码
null,undefined和布尔值
null
与undefined
的区别:
+ `null`是表示一个空的对象,转为数值时为`0`
+ `undefined`是表示“此处无定义”的原始值,转为数值时为`NaN`
代码示例:
Number(undefined) // NaN
Number(null) // 0
在if
语句中,null
与undefined
都会被自动转为false
,相等运行符==
直接报告两者相等。
if (!undefined){
console.log('undefined is false')
}
// result: undefined is false
if (!null){
console.log('null is false')
}
// result: null is false
undefined == null
// result: true
布尔值
真:true
假:false
下列运算符会返回布尔值:
前置逻辑运算符:
!
(Not)相等运行符:
===
,!==
,==
,!=
比较运算符:
>
,>=
,<
,<=
下面六个值被转为false
,其它值都视为true
:
undefiend
null
false
0
NaN
""
或''
(空字符串)
空数组([]
)和空对象({}
)对应的布尔值,都是true
示例代码:
if (''){
console.log("true")
}
// result:不会有输出
if ([]) {
console.log('true');
}
//result: true