JavaScript的数据类型
1. JavaScript基础数据类型
- number:表示
(-2^53, 2^53)
范围内的整数和小数。 - string:字符串,用
""
双引号或''
单引号包裹的字符。 - boolean:布尔值,取值为
true
或false
。 - undefined:表示没有定义。
- null:表示定义了,但内容为空。
(function test() {
// 定义一个number类型变量
let num = 1;
console.log(typeof num);
// 定义一个string类型变量
let str = 'hello';
console.log(typeof str);
// 定义一个boolean类型变量
let b = true;
console.log(typeof b);
// undefined
console.log(typeof c);
// null
let tmp = null;
// typoef null 会返回 object, 这是早期 JavaScript 实现中的一个错误,不要使用 typeof 操作符检测 null 值
console.log(typeof tmp);
// 使用===判断
console.log(tmp === null)
})()
1.1 模版字符串
一般字符串里,会把变量当成普通字符处理。如果需要在字符串里,引用变量的值,则需要使用模版字符串。
(function test() {
let name = '文大奇Quiin';
// 模版字符串,用``包裹,里面的变量用${变量名}格式引用
console.log(`hello, ${name}`);
})()
2. JavaScript引用数据类型
- object:对象类型
(function test() {
// 创建一个对象(方式一)
let student = {
name: '文大奇Quiin',
age: 18
}
console.log(typeof student);
})()
(function test() {
// 利用class关键字创建一个类
class Student {
constructor(name, age) {
this.name = name;
this.age= age;
}
}
// 利用new关键字创建一个对象(方式二)
let student = new Student("文大奇Quiin", 18);
console.log(typeof student);
})()
- Symbol:ES6 新引入的,表示独一无二的值。
(function test() {
// 创建一个Symbol对象
// Symbol可以接受一个参数,表示对Symbol实例的描述
let symbolName = Symbol("name");
console.log(typeof symbolName)
// Symbol 作为对象的属性名,因为Symbol是独一无二,所以对象的属性不会被覆盖
let obj = {
// 把Symbol变量放在中括号里
[symbolName]: "文大奇Quiin"
}
// 获取对象中Symbol属性名的属性值
console.log(obj[symbolName])
})()
- BigInt:ES11 新引入的 ,number 只能表示
(-2^53, 2^53)
,用来可以表示超出这个范围的值。(BigInt类型不能直接与其他类型运算)
(function test() {
// 创建BigInt类型方式一:在数字后面加个n
let bigint1 = 123n;
console.log(typeof bigint1);
// 创建BigInt类型方式二:利用BigInt()
let bigint2 = BigInt(123);
console.log(typeof bigint2);
// BigInt类型不能直接与其他类型运算
// number转成BigInt
let bigint3 = BigInt(2);
console.log(typeof bigint3);
// BigInt转成number
let num = Number(bigint1);
console.log(typeof num);
})()