JavaScript学习笔记—类型转换
类型转换:将一种类型转换为其他类型(一般指字符串、数值和布尔值)
1. 转换为字符串
- 调用toString()方法将其他类型转换为字符串(null和undefined没有toString()方法)
- 调用String()函数将其他类型转换为字符串
原理:
(1)拥有toString()方法的值调用String()函数时会直接调用toString()方法
(2)对于null,则直接转换为"null",对于undefined,则直接转换为"undefined"
let a = 10; // string "10"
a = true; // string "true"
a = 11n; // string "11"
a = undefined; // Uncaught TypeError: Cannot read properties of undefined (reading 'toString')
a = null; // Uncaught TypeError: Cannot read properties of null (reading 'toString')
a = a.toString();
console.log(typeof a, a);
let b = 33; // string "33"
b = null; // string "null"
b = undefined; // string "undefined"
b = true; // string "true"
b = String(b);
console.log(typeof b, b);
2. 转换为数值
- 使用Number()函数将其他类型转换为数值
- 字符串:
- 如果字符串是一个合法数字,会自动转换为对应的数字
- 如果字符串不是合法数字,转换为NaN
- 如果字符串是空串或纯空格的字符串,转换为0
- 布尔值:
- true转换为1,false转换为0
- null:转换为0
- undefined:转换为NaN
- 字符串:
- 专门用来将字符串转换为数值的两个方法
- parseInt(),将字符串转换为整数(自左向右读取一个字符串,直到读取到字符串中所有的有效整数)
- parseFloat(),将字符串转换为浮点数(自左向右读取一个字符串,直到读取到字符串中所有的有效小数)
let a = "123"; // number 123
a = "abc"; // number NaN
a = "3.14"; // number 3.14
a = ""; // number 0
a = " "; // number 0
a = true; // number 1
a = false; // number 0
a = null; // number 0
a = undefined; // number NaN
console.log(typeof a, a);
let b = "123px"; // number 123
b = "a123"; // number NaN
b = "123.45"; // 123
b = parseInt(b);
console.log(typeof b, b);
3. 转换为布尔值
- 使用Boolean()函数讲其他类型转换为布尔值
- 数字:0和NaN转换为false,其余是true
- 字符串:空串转换为false,其余是true
- null和undefined:都转换为false
- 对象:转换为true
let a = 1; // boolean true
a = -1; // boolean true
a = 0; // boolean false
a = NaN; // boolean false
a = Infinity; // boolean true
a = "abc"; // boolean true
a = "true"; // boolean true
a = "false"; // boolean true
a = "0"; // boolean true
a = ""; // boolean false
a = " "; // boolean true
a = null; // boolean false
a = undefined; // boolean false
a = Boolean(a);
console.log(typeof a, a);
所有表示空性的、没有的、错误的值都会转换为false(0、NaN、空串、null、undefined、false)
人们通常会犯错误的值得注意的例子有以下几个:
- 对 undefined 进行数字型转换时,输出结果为 NaN,而非 0。
- 对 "0" 和只有空格的字符串(比如:" ")进行布尔型转换时,输出结果为 true。