一、定义
将其他的数据类型转化为数值
- 使用Number()函数来将其他类型转化为数值,适用于任何类型
- 使用parseInt() -- 将一个字符串转化为一个整数
-解析时,会自作向右读取一个字符串,直到读取到所有的整数位
parseFloat() -- 将一个字符串转化为浮点数
- 使用Number()函数来将其他类型转化为数值
- 转化的情况
-字符串
- 如果字符串是一个各发的数字,就转化为对应数字
- 如果字符串不是合法数字,转化为NaN(例如 ‘abc'就不是合法数字)
- 字符串是空串或纯空格,转化为0
-布尔值
- true转化为1 false转化为0
- null 转化为 0
- undefinded 转化为 NaN
<script>
/*
将其他的数据类型转化为数值
1.使用Number()函数来将其他类型转化为数值
- 转化的情况
-字符串
- 如果字符串是一个各发的数字,就转化为对应数字
- 如果字符串不是合法数字,转化为NaN
- 字符串是空串或纯空格,转化为0
-布尔值
- true转化为1 false转化为0
- null 转化为 0
- undefinded 转化为 NaN
*/
let a = '123' //合法数字
let b = 'abc' //不合法数字
let c = '' //空字符串,转为0
let d = ' ' //空格串,转为0
let e = true //ture 转为 1
let f = false //false 转为0
let g = null //null 转化为 0
let h //undefinded 转化为 NaN
a = Number(a)
b = Number(b)
c = Number(c)
d = Number(d)
e = Number(e)
f = Number(f)
g = Number(g)
h = Number(h)
console.log(typeof a, a)
console.log(typeof b, b)
console.log(typeof c, c)
console.log(typeof d, d)
console.log(typeof e, e)
console.log(typeof f, f)
console.log(typeof g, g)
console.log(typeof h, h)
</script>
- 使用parseInt() -- 将一个字符串转化为一个整数
-解析时,会自作向右读取一个字符串,直到读取到所有的整数位
例如:let a = '123px’
使用 a = Number(a) 那么 a 的值为NaN,
使用 a = parseInt(a) 那么 a 的值为123,
如果是 let a = 'p123px' 自作向右第一个不是数字,
使用 a = parseInt(a) 那么 a 的值为NaN
如果是 let a = '123.123' 有小数部分,
使用 a = parseInt(a) 那么 a 的值为123,只读取到整数部分
<script>
/*
将其他的数据类型转化为数值
1.使用Number()函数来将其他类型转化为数值
- 转化的情况
-字符串
- 如果字符串是一个各发的数字,就转化为对应数字
- 如果字符串不是合法数字,转化为NaN
- 字符串是空串或纯空格,转化为0
-布尔值
- true转化为1 false转化为0
- null 转化为 0
- undefinded 转化为 NaN
专门用来将字符串转换为数值的两个方法
parseInt() -- 将一个字符串转化为一个整数
-解析时,会自作向右读取一个字符串,直到读取到所有的整数位
parseFloat() -- 将一个字符串转化为浮点数
*/
// let a = '123' //合法数字
// let b = 'abc' //不合法数字
// let c = '' //空字符串,转为0
// let d = ' ' //空格串,转为0
// let e = true //ture 转为 1
// let f = false //false 转为0
// let g = null //null 转化为 0
// let h //undefinded 转化为 NaN
// a = Number(a)
// b = Number(b)
// c = Number(c)
// d = Number(d)
// e = Number(e)
// f = Number(f)
// g = Number(g)
// h = Number(h)
// console.log(typeof a, a)
// console.log(typeof b, b)
// console.log(typeof c, c)
// console.log(typeof d, d)
// console.log(typeof e, e)
// console.log(typeof f, f)
// console.log(typeof g, g)
// console.log(typeof h, h)
let a = '123px'
a = Number(a)
console.log(typeof a, a)
let b = '123px'
b = parseInt(b)
console.log(typeof b, b)
let c = 'P123px'
c = parseInt(c)
console.log(typeof c, c)
let d = '123.123'
d = parseInt(d)
console.log(typeof d, d)
</script>