JavaScript 语言的每一个值,都属于某一种数据类型。JavaScript 的数据类型,共有七种。
数值
、字符串
、布尔值
这三种是原始类型。对象
则称为合成类型。undefined
和null
,为两个特殊值。ES6 添加了Symbol
类型的值。
一.概念
1.类型介绍
- 数值(number):整数和小数(比如
1
和3.14
) - 字符串(string):文本(比如
Hello World
) - 布尔值(boolean):表示真伪的两个特殊值,即
true
(真)和false
(假) - undefined:表示“未定义”或不存在,即由于目前没有定义,所以此处暂时没有任何值
- null:表示空值,即此处的值为空
- 对象(object):各种值组成的集合
- 狭义的对象(object)
- 数组(array)
- 函数(function)
2.typeof 运算符
- 确定值类型有三种方式:
①typeof
运算符;②instanceof
运算符;③Object.prototype.toString
方法 - 使用
typeof
运算符打印数值类型:
①数值
打印number
;②字符串
打印string
;③布尔值
打印boolean
;④函数
打印function
;⑤undefined
打印undefined
;⑥对象
打印object
(由于历史原因null
也打印object
);//① typeof 123 // "number" //② typeof '123' // "string" //③ typeof false // "boolean" //④ function f() {} typeof f // "function" //⑤ typeof undefined // "undefined" // ReferenceError: v is not defined typeof v// "undefined" //⑥ typeof window // "object" typeof {} // "object" typeof [] // "object" typeof null // "object"
二. null, undefined 和布尔值
1.null 和 undefined
Ⅰ.异同点
-
undefined
代表未定义;null
代表空,语法效果没有什么区别; -
相同点:①给变量赋值undefined或者null,几乎是等价的;②在if语句中都会转成
false
;③相等运算符==
报告两者相等 -
不同点:①
null
使用Number转换为0;②undefined
使用Number转换为NaN; -
验证上述范例:
//① var a = undefined; // 基本等价 var a = null; //② if (!undefined) { console.log('undefined is false'); } // undefined is false if (!null) { console.log('null is false'); } // null is false console.log(undefined == null) // true //③ console.log(Number(null)) // 0 console.log(Number(undefined))// NaN
Ⅱ.使用场景
-
null
使用场景:在调用函数时,没有值的时候,可传入null表示无值; -
undefined
表示未定义:典型场景,①变量声明,但没有赋值;②调用函数时,应该提供的参数没有提供,该参数等于 undefined;③对象没有赋值的属性;④ 函数没有返回值时,默认返回 undefined// 变量声明了,但没有赋值 var i; i // undefined // 调用函数时,应该提供的参数没有提供,该参数等于 undefined function f(x) { return x; } f() // undefined // 对象没有赋值的属性 var o = new Object(); o.p // undefined // 函数没有返回值时,默认返回 undefined function f() {} f() // undefined
2.布尔值
Ⅰ.返回boolean的逻辑运算符
- 真为
true
和假为false
- 返回boolean的逻辑运算符
- 前置逻辑运算符:
!
- 相等运算符:
===
,!==
,==
,!=
- 比较运算符:
>
,>=
,<
,<=
- 前置逻辑运算符:
Ⅱ.boolean自动转换规则
-
如下六个值undefined,null,false,0,NaN,""或’’(空字符串)自动转换为false;其余转换为true
-
验证如上范例,空数组
[]
,空对象{}
都会自动转换为trueif ('') { console.log('true'); } // 没有任何输出 if ([]) { console.log('true'); } // true if ({}) { console.log('true'); } // true