数据类型 - JavaScript

值类型(基本类型):字符串(string)、数字(number)、布尔(boolean)、空(null)、未定义(undefined)、Symbol。

引用数据类型(对象类型):对象(Object)、数组(Array)、函数(Function),还有两个特殊的对象:正则(RegExp)和日期(Date)。

number

正数 负数 小数

NaN 不等于任何值,包括自身

string

单引号或双引号

1
2
let a = "Hello";
let b = 'World';

转义:

1
2
let a = "\"";
let b = '\'';

拼接:

1
2
3
4
5
6
7
let a = "Hello";
let b = 'World';
let c = a + b; // 'HelloWorld'

let d = 666;
let e = a + d; // 字符串 + 数字 仍是字符串
let f = d + a; // 数字 + 字符串 也是

模板字符串:

ES2015

字符串插值:

1
2
3
let a = 18;
`我今年${a}岁了`
`我今年${a - 10}岁了`

多行字符串:

1
2
3
4
5
`
hahaha
hahah
hahahah
`

undefined

只声明,没赋值

1
let a;

null

空类型(赋值了,undefined是没赋值的)

1
let obj = null;

typeof 检测类型

1
2
let a = 18;
console.log(typeof a);

数据类型转换

隐式转换

+ 其中一边为字符串,转换成字符串

- * / 转换成数字类型

+ 作为正号可以转换为数字类型

显式转换

Number() 转为数字类型,NaN也是数字类型

parseInt() 只保留整数

parseFloat() 浮点数

Number() 遇到字母会NaN

parset 仅在以数字开头时,遇到字母会忽视,常用于过滤单位

String() 变量.toString() 转换为字符串

toString(num) 转换成 num进制 少用