JavaScript 基础
Document
运算符
深入数据和类型
函数进阶
原型、继承
类
浏览器存储
Web API
事件
错误处理
异步编程
网络请求
模块
练习
实例
工具与规范
软件架构模式
设计模式
JavaScript 中的数据被区分成各种各样的类型,如此一来能对不同类型的数据进行不同的操作。比如对于数字的数据,我们希望能对其进行加减乘除,因此有便有了数字类型。对于字符串的数据,我们希望能对其进行拼接,或查询是否包含某个字符的操作,因此便有了字符串类型。
$$tip
一个变量的类型由它所赋值的数据确定。
$$
JavaScript 中的类型分为原始类型与对象类型两大类。
原始(值)类型:
- String:字符串类型,保存文本的字符序列,例如:
"三眼鸭的编程教室"
- Number:数字类型,整数或浮点数,例如:
42
或者3.14159
。 - BigInt:大整数类型。
- Boolean:布尔类型,只有两个值
true
和false
。 - undefined:未定义类型,变量未赋值时的值。
- null:空值类型,与
undefined
类似。 - Symbol:标识符类型,实例是唯一且不可更改的类型。
对象(引用)类型:
包括并不限于 object
、 function
、 arrary
等等。
$$tip 非原始类型都继承自对象。
原型继承将在往后的章节学习到。 $$
类型判断
通常情况下,一般使用 typeof
或 instanceof
来判断一个变量的类型。
typeof
typeof
是一个操作符,右边接变量,返回一个字符串类型描述。
typeof "三眼鸭" // string
typeof 123 // number
typeof 1000n // bigint
typeof true // boolean
typeof undefined // undefined
typeof null // object
typeof Symbol() // symbol
typeof [] // object
typeof {} // object
typeof new Function() // function
typeof new Date() // object
typeof new RegExp() // object
$$warning
由于历史遗留问题,typeof
并不能很完美地返回想要的结果:
- 对于原始类型,
null
类型返回object
,其余返回正确的类型。 - 对于对象类型,除了
function
均返回object
。
$$
instanceof
instanceof
用来判断变量是否是某个类型的实例,如果是则返回 true
,否则返回 false
。相对于 typeof
,instanceof
用来判断对象类型。
$$tip
所有的非原始类型都同时属于 Object
类型。
$$
new Array() instanceof Array // true
new Function() instanceof Function // true
new Number(123) instanceof Number // true
new Date() instanceof Date // true
$$tip
instanceof
运算符的原理是检测构造函数的 prototype
属性是否出现在某个实例对象的原型链上。有关原型链的知识点后面会学习到。
$$
练习
- 判断以下代码的结果。
typeof [2, 4, 8];
[2, 4, 8] instanceof Array;
typeof 123;
123 instanceof Number;
typeof new Number(123);
new Number(123) instanceof Number;
typeof null;
null instanceof Object;
$$answer
$$jsdemo$$
$$edit$$
console.log(typeof [2, 4, 8]) // object, 非原始类型除了 function 均为 object
console.log([2, 4, 8] instanceof Array) // true, 数组的类型为 Array
console.log(typeof 123) // number, 原始类型 number
console.log(123 instanceof Number) // false, 123 为原始类型
console.log(typeof new Number(123)) // object, new Number(123) 与 123 的类型不同,它属于对象(引用)类型
console.log(new Number(123) instanceof Number) // true, new Number(123) 属于对象(引用)类型
console.log(typeof null) // object,null 虽为原始类型但 typeof 为 object
console.log(null instanceof Object) // false, null 为原始类型, 不属于对象(引用)类型
$$