JS基础数据类型

在JavaScript中,数据类型分为两类:基本数据类型和引用数据类型。本文将重点介绍JavaScript中的基础数据类型,即基本数据类型。
基本数据类型
JavaScript中的基本数据类型有6种,分别是undefined、null、boolean、number、string和symbol。
1. undefined
undefined代表的是一个声明但未赋值的变量的值。例如:
let a;
console.log(a); // undefined
2. null
null代表的是空值,它是一个关键字,不是一个关键字。当你想显式地指定一个空值时可以使用null。例如:
let b = null;
console.log(b); // null
3. boolean
boolean代表的是逻辑上的真和假,只有两个值:true和false。例如:
let c = true;
let d = false;
console.log(c); // true
console.log(d); // false
4. number
number代表的是数字,包括整数和浮点数。例如:
let e = 123;
let f = 3.14;
console.log(e); // 123
console.log(f); // 3.14
5. string
string代表的是字符串,用单引号(')或双引号(")括起来的任意文本。例如:
let g = 'Hello';
let h = "World";
console.log(g); // Hello
console.log(h); // World
6. symbol
symbol是ES6新增的数据类型,表示独一无二的值。例如:
const sym = Symbol('foo');
console.log(sym); // Symbol(foo)
数据类型检测
在JavaScript中,我们可以使用typeof操作符来检测一个变量的数据类型。例如:
let n = 123;
console.log(typeof n); // number
let s = 'Hello';
console.log(typeof s); // string
let b = true;
console.log(typeof b); // boolean
let sym = Symbol('bar');
console.log(typeof sym); // symbol
类型转换
在JavaScript中,数据类型可以相互转换。有两种类型的转换:隐式类型转换和显式类型转换。
1. 隐式类型转换
隐式类型转换是指在运行过程中自动进行的数据类型转换。例如:
let x = 10 + "20"; // 1020,数字和字符串相加时,数字会被隐式转换为字符串
2. 显式类型转换
显式类型转换是我们手动指定的数据类型转换。例如:
2.1 转换为字符串
- 使用
String()函数
let num = 123;
let str = String(num);
console.log(str); // "123"
- 使用
toString()方法
let num = 123;
let str = num.toString();
console.log(str); // "123"
2.2 转换为数字
- 使用
Number()函数
let str = "123";
let num = Number(str);
console.log(num); // 123
- 使用
parseInt()函数或parseFloat()函数
let str = "3.14";
let numInt = parseInt(str);
let numFloat = parseFloat(str);
console.log(numInt); // 3
console.log(numFloat); // 3.14
2.3 转换为布尔值
- 使用
Boolean()函数
let val = 0;
let bool = Boolean(val);
console.log(bool); // false
NaN和Infinity
在JavaScript中,有两个特殊的数字值:NaN(Not-a-Number)和Infinity(正无穷)。NaN表示一个非数字的值,Infinity表示正无穷大。
console.log(0 / 0); // NaN
console.log(1 / 0); // Infinity
总结
在JavaScript中,基本数据类型包括undefined、null、boolean、number、string和symbol。我们可以使用typeof操作符来检测数据类型,使用类型转换函数来进行数据类型转换。此外,JavaScript还有特殊的数字值NaN和Infinity。
极客笔记